Skip to content

feat(api): MCP tool loop so API-key runs can read Confluence, Jira and secfoo-memory - #205

Open
Labu1 wants to merge 2 commits into
secfoo-com:mainfrom
Labu1:repodestek/issue-123
Open

Labu1 wants to merge 2 commits into
secfoo-com:mainfrom
Labu1:repodestek/issue-123

Conversation

@Labu1

@Labu1 Labu1 commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

Closes #123

What does this change, and why?

The README says Confluence, Jira and SharePoint reach the agent through MCP, but that was only true for --agent claude. The api agent is the GitHub Action default and the only option without a coding-agent CLI. It was a fixed collect_files -> assess -> request_fix pipeline with no tool loop. --confluence pages could only be reported as "could not be reached", and the secfoo-memory tools were never available.

This PR gives the api agent its own MCP client and a tool loop:

  • MCP client (src/secfoo/agents/mcp_tools.py): uses the official mcp SDK to connect to every server from effective_servers() over stdio, streamable HTTP or SSE, list its tools and run calls. The SDK is async and the graph is sync, so one worker thread owns the event loop. A single task opens, serves and closes all sessions, which anyio's task groups require. A server that can't be reached is skipped and named in stderr.log. The run continues without it.
  • Tool loop (src/secfoo/agents/api.py): a new tool node (assess -> tool -> assess). Server tools are passed to litellm.completion(tools=...) as function tools. The budget is 20 calls and 5 minutes of tool use. After that the model is told the budget is spent, and the last call uses tool_choice="none". Calls over the budget in the same turn still get an answer ("Not run"), so every tool_call_id is matched.
  • Read-only by construction: only tools the server annotates readOnlyHint: true are offered. A new optional per-server tools = [...] key in [[mcp_servers]] is an explicit allowlist that replaces the annotation check for that server. The default secfoo-memory server lists its three lookup tools. A tool the model names that wasn't offered is refused and logged.
  • Context size: tool results count toward --max-input-tokens, and the size check now runs before every completion call. A result over 40,000 characters is truncated with a visible marker. A result that would push the conversation over the limit is dropped, and tool use ends.
  • Coverage honesty: every call is written to stderr.log (server, tool, argument summary, bytes returned, status). The same log goes back to the model after each round, and the system prompt tells it to describe a source as read only if the log shows it was retrieved.
  • Usage: tokens and cost add up over every completion call in the conversation.
  • api is now in MEMORY_CAPABLE_AGENTS, so the pattern-memory guidance is rendered for it.
  • mcp>=1.12,<2 is added to the base dependencies. The 2.x SDK reworks the client transports this module uses.
  • Docs: README "Context, not just code", the MCP table and memory section in docs/REFERENCE.md, the api row in docs/agents.md, and config.example.toml.

Not done here: the manual run against the Atlassian Rovo server with a screenshot of the coverage section, which the issue lists under "Done when". That needs real Atlassian and model credentials. The behaviour is covered with a fake stdio MCP server instead.

Testing

Ran pytest in a clean Linux container: the 4 remaining failure(s) also occur on the base branch without this change; no new failures are introduced.

  • pytest tests passes
  • ruff check . passes
  • Added/updated tests for the behavior change

New tests in tests/test_agents/test_api.py use a small FastMCP stdio server (tests/test_agents/fake_mcp_server.py) and a fake LiteLLM. They check that:

  • tools are discovered;
  • a --confluence URL leads to a tool call, and the result and log reach the model;
  • write-capable and unannotated tools are never offered, and the allowlist replaces the annotation check;
  • the call budget and the wall-clock limit stop the loop;
  • results are truncated, or dropped when over --max-input-tokens;
  • cost adds up over every call;
  • an unreachable server is skipped.

tests/test_settings.py covers the new tools key, and tests/test_memory.py is updated for api now being memory-capable.


This PR was prepared with AI assistance (Claude) and reviewed by me before submitting.

…d secfoo-memory

The api agent was a fixed collect -> assess -> request_fix pipeline
with no tool loop. MCP servers from [[mcp_servers]] (and
secfoo-memory) only worked with --agent claude, so in CI, where api
is the norm, --confluence pages could only be reported as "could not
be reached".

The api agent now connects to every server from effective_servers()
with the official mcp SDK (stdio, streamable HTTP, SSE). One worker
thread holds the async sessions. The server tools go to LiteLLM as
function tools, and a new `tool` node runs the model's calls:
assess -> tool -> assess.

- Read-only by construction: only tools annotated readOnlyHint are
  offered, unless the server entry lists tools in the new
  `tools = [...]` allowlist. secfoo-memory lists its three lookups.
- Bounded: 20 tool calls and 5 minutes per run. After that the model
  is told the budget is spent and the last call uses tool_choice=none.
- Tool results count toward --max-input-tokens, which is now checked
  before every completion call. A result over 40,000 characters is
  truncated with a visible marker. A result that would exceed the
  limit is dropped and ends tool use.
- Every call is logged (server, tool, arguments, bytes, status) to
  stderr.log. The same log goes back to the model, so the coverage
  section can only claim documents a tool returned.
- Tokens and cost add up over every completion call.
- api now counts as memory-capable, so memory guidance is rendered.

Tests use a small FastMCP stdio server and a fake LiteLLM. Docs
(README, REFERENCE, agents.md, config.example.toml) say api supports
MCP.

Fixes secfoo-com#123.
@Labu1
Labu1 requested a review from vsn411 as a code owner November 27, 2026 07:58
Comment thread src/secfoo/agents/mcp_tools.py Fixed
Only the errors that can actually end the MCP client's event loop are
caught now: Exception, asyncio.CancelledError and BaseExceptionGroup (the
builtin on 3.11+, the exceptiongroup backport on 3.10). KeyboardInterrupt
and SystemExit are no longer swallowed. Tests cover both cases.
@Labu1

Labu1 commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @github-advanced-security[bot]. _thread_main in src/secfoo/agents/mcp_tools.py no longer catches BaseException. It now catches a named tuple, _WORKER_STOP_ERRORS: Exception, asyncio.CancelledError and BaseExceptionGroup (the builtin on 3.11+, the exceptiongroup backport on 3.10). The SDK's anyio transports can raise cancellations or exception groups out of asyncio.run(), so those still end tool use without failing the run. KeyboardInterrupt and SystemExit now propagate. The # noqa: BLE001 is gone. New tests in tests/test_agents/test_api.py check that an ordinary error and a cancellation are recorded in toolbox.errors, that a KeyboardInterrupt is re-raised, and that _ready is set in both cases.

Ran pytest in a clean Linux container: the 4 remaining failure(s) also occur on the base branch without this change; no new failures are introduced.

@vsn411

vsn411 commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator

Thanks, this is a careful piece of work, and it closes the biggest gap in the "context, not just code" story. Things we especially liked:

  • one worker thread owning the event loop, with the sessions opened and closed in the same task;
  • read-only by annotation, with an explicit allowlist that replaces the check;
  • every tool_call_id answered, even when over budget;
  • tool results counted toward --max-input-tokens;
  • the tool-call log handed back to the model for the coverage section;
  • tests against a real FastMCP stdio server.

CI is green on all platforms.

One design point before we merge, then housekeeping:

  1. Cost grows with every tool round. Each assess call resends the whole conversation, including the full target source. Twenty single-call rounds can send the source about twenty times. max_input_tokens has no default, and --max-cost is only checked after the run. Anyone who has run secfoo memory login now gets the tool loop on every api run, because api is in MEMORY_CAPABLE_AGENTS and the memory server is a default. So their spend could jump with no change on their side. Could you add a guard?

    • Stop the tool phase once the conversation's cumulative input tokens reach a multiple of the first call's, e.g. 4×. Then tell the model the budget is spent, as you already do.
    • Make the call budget configurable ([agents.api].tool_call_budget), keeping 20 as the default if you like.
    • In TOOLS_NOTE, ask the model to batch independent lookups into one turn. Your tool node already handles several calls per turn.
    • Log the number of rounds and the total input tokens in stderr.log.

    Prompt caching (cache_control on the source message for Anthropic models) would cut the cost a lot too. That can be a follow-up.

  2. Rebase on main. The branch is behind. feat(mcp): support Codex MCP sync and canonical MCP support matrix (#124) #195 (Codex MCP sync) touches the same README paragraph, the same docs/REFERENCE.md MCP table and the same docs/agents.md rows, and it will probably merge first. Please rebase after it lands.

  3. Manual Rovo run. You're right that it needs real credentials. Don't block on it: we can do that run ourselves after merge and post the coverage-section screenshot on MCP for the api agent: a tool loop so API-key runs can read Confluence, Jira, SharePoint and secfoo-memory too #123. Please change "Closes MCP for the api agent: a tool loop so API-key runs can read Confluence, Jira, SharePoint and secfoo-memory too #123" to "Part of MCP for the api agent: a tool loop so API-key runs can read Confluence, Jira, SharePoint and secfoo-memory too #123" so the issue stays open for that step.

Nits, fine to leave:

  • tool_deadline starts at collect_files, so a slow first completion uses up part of the 5-minute tool phase. Starting it at the first tool call would match the docs ("5 minutes of tool use").
  • If start() times out waiting for _ready, the worker can still fill self.tools later. A flag that ignores late tools would make it deterministic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MCP for the api agent: a tool loop so API-key runs can read Confluence, Jira, SharePoint and secfoo-memory too

3 participants