Skip to content

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

Merged
vsn411 merged 5 commits into
secfoo-com:mainfrom
Labu1:repodestek/issue-123
Nov 29, 2026
Merged

vsn411 merged 5 commits into
secfoo-com:mainfrom
Labu1:repodestek/issue-123

Conversation

@Labu1

@Labu1 Labu1 commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Part of #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.

…igurable

Every assess call resends the whole conversation, source included, so the
tool phase now ends once the input tokens sent reach 4x the first call's.
The call budget is read from [agents.api].tool_call_budget (default 20,
0 turns tools off). The tools note asks the model to batch independent
lookups, and stderr.log records the rounds, the total input tokens sent and
which limit ended the tool phase.

Also starts the 5-minute tool clock at the first tool call, and stops
McpToolbox from publishing tools after start() has given up waiting.
@Labu1

Labu1 commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

@vsn411 thanks for the careful review. Here's what changed:

1. Cost guard

  • Token cap: the tool node in src/secfoo/agents/api.py now tracks the input tokens of every assess call. It uses the provider's number, or an estimate when the provider reports none, so the guard still works then. Once the total reaches TOOL_INPUT_TOKEN_MULTIPLE (4) times the first call's, that round's calls are answered with the usual "not run" message. The model then gets the budget-spent note and tool_choice=none, as before.
  • Configurable budget: [agents.api].tool_call_budget is parsed in settings.py as a non-negative integer, default 20. 0 turns the tool loop off without starting any MCP server, which also lets memory users opt out for api only.
  • Batching: TOOLS_NOTE now asks the model to put independent lookups into one turn and explains why.
  • Logging: stderr.log gets one summary line, e.g. mcp tool phase: 3 round(s), 2 of 20 call(s) used, 5,200 input tokens sent in total (1,000 on the first call); ended: ..., naming which limit ended the phase.
  • Docs: README, docs/REFERENCE.md, docs/agents.md and config.example.toml are updated.

I left prompt caching for a follow-up, as you suggested.

2. Rebase: I'll rebase onto main once #195 lands.

3. Manual Rovo run: agreed, and thanks for offering to do it. I changed the PR description to "Part of #123", so #123 stays open for that run.

Nits: I did both.

  • tool_deadline now starts at the first tool call.
  • McpToolbox.start() and the worker now share a lock and an _abandoned flag. Either the tools are published before start() gives up, or the worker closes its sessions and exits without publishing anything.

Tests:

  • In tests/test_agents/test_api.py: the token cap stopping the third round; the budget read from the config; budget 0 turning tools off; the batching note; the summary line; late tools never being offered.
  • In tests/test_settings.py: parsing and rejecting tool_call_budget values.

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 and others added 2 commits November 29, 2026 09:43
Log a session that fails to close at debug level instead of a silent
pass (S110), and type McpToolbox.__enter__ as Self (PYI034).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@vsn411
vsn411 merged commit 0f3a7c8 into secfoo-com:main Nov 29, 2026
16 checks passed
@vsn411

vsn411 commented Nov 29, 2026

Copy link
Copy Markdown
Collaborator

Merged, thank you! The cost guard is exactly right:

  • the 4× input-token cap;
  • [agents.api].tool_call_budget, where 0 turns tools off;
  • the batching instruction;
  • the stderr summary line;
  • the clock starting at the first tool call;
  • the lock that keeps late tools from being offered.

To get it in today, I pushed one small commit (c51071d) after #206 made ruff blocking:

  • _close_quietly logs at debug level instead of a silent pass (S110);
  • McpToolbox.__enter__ is typed Self (PYI034);
  • current main is merged in.

#123 stays open for the manual Rovo run. We'll do that one and post the coverage screenshot there.

vsn411 added a commit to saryeljaramany/secfoo that referenced this pull request Nov 29, 2026
Resolve the docs conflicts with secfoo-com#205 (api MCP tool loop), secfoo-com#209 (Models
column) and secfoo-com#214: keep both the api and Codex MCP text. Also drop the
header row that the secfoo-com#209 merge duplicated in docs/agents.md, and say
'remove the entry, then run sync again' for key rotation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

3 participants