Skip to content

adapters: add FastMCP server middleware and client integration - #78

Open
angelnicolasc wants to merge 3 commits into
GenAI-Security-Project:integrationfrom
angelnicolasc:samples/python-guardian-fastmcp
Open

angelnicolasc wants to merge 3 commits into
GenAI-Security-Project:integrationfrom
angelnicolasc:samples/python-guardian-fastmcp

Conversation

@angelnicolasc

@angelnicolasc angelnicolasc commented Sep 10, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #135

What changed

Rebased onto current integration (0.1.5) and moved from the earlier samples/python-guardian-fastmcp/ sketch (and its .github/workflows/samples.yml) into a first-class FastMCP integration under adapters/src/acs/integrations/fastmcp/, following adapters/README.md#contributing-a-new-adapter.

Since #22 landed acs.core, acs.client, and acs-example-guardian under adapters/ — and #118 settled the HKDF/HMAC-SHA256 wire parameters — carrying a second unsigned stdlib Guardian under a third top-level samples/ tree would duplicate adapters/ and re-introduce #70. Building directly on acs.core and acs.client gives FastMCP the full signed v0.1.0 wire contract out of the box against both acs-example-guardian and agt-go, with zero .github/workflows/ changes.

Surfaces added

  • ACSFastMCPMiddleware (adapters/src/acs/integrations/fastmcp/adapter.py): attaches via mcp.add_middleware(...) and governs every tools/call in on_call_tool (pre-execution steps/toolCallRequest, post-execution steps/toolCallResult linked via request_id_ref, steps/sessionStart / steps/sessionEnd).
  • GovernedFastMCPClient: wraps fastmcp.Client (async with GovernedFastMCPClient(client) as governed:) sharing the exact same _FastMCPSession core.
  • Optional extra & packaging: fastmcp = ["fastmcp>=2.9,<5"] in adapters/pyproject.toml (with adapters/uv.lock updated; zero dependency conflict with nat or pqc), registered under [project.entry-points."acs.integrations"] and adapters/run_conformance.py (run_conformance.py fastmcp).
  • Docs: adapters/docs/fastmcp/README.md (with explicit Conformance Status table matching the Claude Code adapter format) and adapters/docs/fastmcp/mapping.md.

Measured checks

Measured on 22ef253 (Python 3.12, fastmcp 4.2.5, acs-adapters 0.1.5):

Check Result
3 tool calls in one scope 1 handshake/hello, 1 sessionStart, 3 toolCallRequest, 3 toolCallResult (request_id_ref matched), 1 sessionEnd
5 concurrent asyncio.gather calls (0.4s slow handshake) 1 handshake/hello, event loop ticked continuously (asyncio.to_thread)
ACS_DISABLED=1 (with explicit guardian_url / default_deny kwargs) 0 requests to Guardian (Config.from_env + dataclasses.replace)
ACS_STARTUP_POSTURE=proceed with Guardian down Allowed, audited; default startup posture refuses
All 6 GUARDIAN_REFUSAL_CODES (-32000..-32700) under ACS_DEFAULT_DENY=0 All 6 fail closed; tool never runs
Unsigned Guardian response under default_deny=False Fails closed; tool never runs
Allowed tool raising ValueError Propagates as ValueError (never masked as ACSGuardianDenied); toolCallResult emits exit_status: "failure"
Pre-execution MODIFY (parameter_overrides) + post-execution MODIFY (modified_content) Applied on live FastMCP ToolResult; §6.3 composition violations fail closed (modify_unsupported)
JSON key collision ({1: "a", "1": "b"}) Fails closed (envelope_not_signable) before sending
Live in-memory FastMCP + Client(mcp) + acs-example-guardian Benign tool runs; rm -rf / denied pre-execution (executed == ["echo hello"])
CaptureGuardian emission conformance (advertised == emitted, independent HMAC) All envelopes valid against specification/v0.1.0/
uv run lint-imports 2 contracts kept, 0 broken (integrations -> client -> core; no guardian/examples/testing imports)
uv run python -m unittest discover -s tests/integrations/fastmcp -t . 17 passed, 0 skipped, 0 failed
Base env without [fastmcp] extra (uv sync --locked --group test) 34 passed (test_emission, test_adapter, test_metadata, test_run_conformance)
uv build --wheel Built acs_adapters-0.1.5-py3-none-any.whl cleanly

Conformance boundaries (stated plainly)

  • Emission conformance, not full certification: test_emission.py and test_live.py validate every emitted byte against specification/v0.1.0/ via CaptureGuardian and test live round-trip enforcement against acs-example-guardian. They do not claim requirement-by-requirement certification.
  • Host boundary: FastMCP intercepts MCP tools/call, not LLM prompt/response turns, so userMessage and agentResponse are neither emitted nor advertised (advertised == emitted).
  • Wrapped MCP: Like the existing adapters, MCP tools/call flows through steps/toolCallRequest / steps/toolCallResult and records profile_claim_degraded once per session via record_mcp_use. Non-tool MCP methods (resources/read, prompts/get) are not wrapped.
  • Dispositions: ask and defer substitute to deny with audit at the FastMCP boundary.

Checklist

  • Commits carry Signed-off-by (DCO)
  • Targets integration
  • No .github/workflows/ modifications
  • uv run lint-imports passes (2 kept, 0 broken)
  • Tested with and without the optional fastmcp extra

@rocklambros

Copy link
Copy Markdown
Collaborator

Thank you for this, and for the way it is framed. Acknowledging quickly so you are not waiting on silence, with the caveat that the OWASP relaunch call runs today and considered review will come after it.

A few things worth saying plainly, because they are not generic praise.

You answered an ask before it was made. The call later today asks for exactly this: the reference implementation runs on Bun, and Python was named as open and unclaimed. You got there first, from reading the repository.

You targeted integration. Almost nothing else in the tracker did. That means you read CONTRIBUTING.md, and it is worth knowing that landed.

The fail-closed posture is the interesting part. The AGT reference implementation defaults to proceed, which means a Guardian that is down stops governing silently. That default is contested and is being decided in #32 and #37 by Day 30. A second implementation that chose the opposite default is useful evidence in that argument, not just a stylistic difference. Please say in the thread why you chose it.

On your question, which was the right one to ask. The distinction the team has been drawing is that a reference implementation carries policy and demonstrates the contract end to end, while an adapter slots into an existing harness and emits the wire. A Guardian with a pluggable policy plus a client wrapper is the first shape, not the second, so reference-implementations/python-fastmcp/ reads more accurate to me than a third top-level samples/ tree. Treat that as one maintainer's reading rather than a decision. The Spec workstream leads own it, and #22 is still adding adapters/, so all three trees want settling together rather than one at a time. Do not restructure yet.

One heads-up on review scope. The pull request adds .github/workflows/samples.yml. CI runs with write access to the repository, so .github/ carries required owner review and gets read more slowly and more carefully than the rest. That is not an objection, just so the pace does not read as disinterest.

Two things that would help while this waits. Say a word about what the conformance suite asserts and what it does not, since the project is trying to be careful about the difference between emission conformance and requirement-by-requirement conformance. And if you have run this against a real FastMCP client rather than only the tests, that is worth writing down.

Labelled type:refimpl. It is not marked accepted yet, which under the process here means a maintainer has not yet committed the project to the work rather than anything about its quality.

@rocklambros rocklambros added the type:refimpl Reference implementation or adapter work label Sep 10, 2026
@rocklambros

Copy link
Copy Markdown
Collaborator

Cross-linking for visibility: the kick-off onramp issues are now filed, and #86 asks for exactly this work. It went up after your pull request, so this is a record that you got there first rather than a duplicate request.

@rocklambros

Copy link
Copy Markdown
Collaborator

@angelnicolasc This was missing an issue to reference, so I filed #135 for it and accepted it. Could you add a line to the description saying Closes #135? That links the two, closes the issue when this merges, and stops the intake bot from reading the PR as untriaged. I'd have added it myself, but the description is yours.

@dtduc-git

Copy link
Copy Markdown

Hi @angelnicolasc — I read through this PR and the sample Guardian it adds; nice work getting there first. I'd like to help take the Python side past the sample into a full port for #86, and wanted to coordinate before starting, as @rocklambros asked on #86.

Is this still active on your end?

  • If yes: I'll build on this code rather than fork the effort. The shape I'd aim for: the ACS-Core items in docs/spec/conformance.md (all 19 hooks, five dispositions, SessionContext chain, replay protection, baseline HMAC signature, wrapped MCP), a conformance table like the agt-go port's, and the external mode of the conformance harness (ACS_CONFORMANCE_GUARDIAN_URL, the approach Add a Go Guardian reference implementation #169 adds) as the definition of done.
  • If you've moved on: I'll take it forward from this code, and keep your authorship on whatever carries over.

@rocklambros — one structural question while you're here: #86's note says the samples/ vs reference-implementations/ decision sits with the Spec workstream. Unless that's decided otherwise, I'd follow the agt-go precedent and build under reference-implementations/agt-python/, with samples/python-guardian-fastmcp/ staying the sample it is.

@rocklambros rocklambros changed the title samples: Python Guardian agent plus FastMCP client instrumentation samples: Python Guardian agent plus FastMCP client instrumentation . Oct 5, 2026
@rocklambros rocklambros changed the title samples: Python Guardian agent plus FastMCP client instrumentation . samples: Python Guardian agent plus FastMCP client instrumentation Oct 5, 2026
@rocklambros

Copy link
Copy Markdown
Collaborator

Thanks for the Python Guardian sample! The conformance tests you built are exactly the kind of thing that catches real gaps.

One process note: CONTRIBUTING.md says code contributions need to link to an accepted issue (one with a status:accepted label). Your PR doesn't reference one yet, so it'll sit in the queue until that gets sorted.

Two paths forward:

  1. Check the help wanted issues for something that already matches what you're doing
  2. Open a Discussion about where Python samples should live, then file an issue once that's settled

Your question about whether this belongs in samples/ or reference-implementations/ is a good one to start with in Discussions. The maintainers can weigh in and that becomes the accepted issue you link back to.

No rush on this, and the work itself looks solid. Just needs the issue connection to move forward.

Signed-off-by: angelnicolasc <angelnicolasc@users.noreply.github.com>
Signed-off-by: angelnicolasc <angelnicolasc@users.noreply.github.com>
@angelnicolasc
angelnicolasc force-pushed the samples/python-guardian-fastmcp branch from 0d89803 to f328c6d Compare November 24, 2026 20:02
@angelnicolasc angelnicolasc changed the title samples: Python Guardian agent plus FastMCP client instrumentation adapters: add FastMCP server middleware and client integration Nov 24, 2026
@angelnicolasc

Copy link
Copy Markdown
Collaborator Author

@rocklambros @dtduc-git Thanks for the thoughtful notes earlier — sorry for the delay picking this back up.

Because integration has moved forward significantly since September (#22 merged adapters/ with acs.core, acs.client, and acs-example-guardian; #118 settled HKDF/HMAC-SHA256; and the November 3 call settled fail-closed as the default in #32), keeping a separate unsigned stdlib Guardian under a third top-level samples/ tree plus .github/workflows/samples.yml no longer made sense. It would duplicate adapters/ and re-introduce the #70 unsigned-wire gap.

Instead, I rebased #78 onto current integration (0.1.5) and reshaped it into a FastMCP integration under adapters/src/acs/integrations/fastmcp/ following adapters/README.md#contributing-a-new-adapter:

  • Both server and client seams: ACSFastMCPMiddleware (on_call_tool) and GovernedFastMCPClient (call_tool), sharing one _FastMCPSession engine over acs.core + acs.client (full HKDF+HMAC-SHA256 wire signing, off-event-loop via asyncio.to_thread, 1 handshake per session, Config.from_env preserved via dataclasses.replace, tool exceptions propagated unchanged, and all 6 GUARDIAN_REFUSAL_CODES failing closed).
  • Direct answers to your three questions, @rocklambros:
    1. Fail-closed rationale: a silent degradation to allow when the Guardian is unreachable or refuses a step turns any availability fault or malformed input into a policy bypass — which now aligns directly with the November 3 decision in [Bug] §6.4 conflates Guardian refusal with decision failure; refusals are attacker-reachable and should fail closed #32.
    2. Conformance scope: tests/integrations/fastmcp/test_emission.py and test_live.py verify emission conformance against specification/v0.1.0/ via CaptureGuardian (including advertised == emitted and independent HMAC verification) plus live round-trip enforcement, not requirement-by-requirement certification. That boundary is stated explicitly in adapters/docs/fastmcp/README.md.
    3. Real FastMCP execution: tests/integrations/fastmcp/test_live.py runs against a real in-memory FastMCP (4.2.5) server + Client(mcp) + acs-example-guardian (covering allow, pre-execution deny on rm -rf /, modify argument overrides, modify output rewriting, post-tool output withholding, and tool exception propagation).
  • Zero .github/ changes: removed .github/workflows/samples.yml completely.
  • Scope vs. Port the AGT reference implementation to Python #86 / Add a Python Guardian reference implementation #183 (@dtduc-git): this stays strictly on the FastMCP adapter side (adapters/src/acs/integrations/fastmcp/), leaving Port the AGT reference implementation to Python #86 and Add a Python Guardian reference implementation #183 completely clear for the full AGT Python Guardian port with zero overlap.

@rocklambros I added Closes #135 to the description as requested — happy to keep it linked there (re-scoping #135 to the FastMCP adapter now that acs-example-guardian lives in adapters/) or link a fresh adapter issue if you prefer. Once CI checks settle I'll take this out of draft.

@github-actions github-actions Bot added the status:needs-triage Not yet triaged. Applied by the issue forms label Nov 24, 2026
@github-actions

Copy link
Copy Markdown

Thanks for this. It is queued rather than ignored until a lead reads it, and the lead may close it. No lead has reviewed this pull request, and it references no issue a lead assigned to you. Under Part 2 of the Code of Conduct, a pull request that changes behavior, normative text, or code starts from an issue labeled status:accepted that a lead assigned to you before you opened or reopened it. If a lead closes this one, you can reopen it once a lead assigns the work. An editorial fix needs no issue. If a check below fails, please fix it.

…v.lock

Signed-off-by: angelnicolasc <angelnicolasc@users.noreply.github.com>
@angelnicolasc
angelnicolasc marked this pull request as ready for review November 24, 2026 20:26
@github-actions

Copy link
Copy Markdown

This pull request's description says it closes #135, which is on the project roadmap. When it merges, GitHub closes that issue and the roadmap counts it as delivered. Please confirm the change delivers the whole issue before merging.

@rocklambros

Copy link
Copy Markdown
Collaborator

Hi Nick, thanks for sticking with this. #135 is accepted and on the Language ports milestone, but nobody is assigned to it. CONTRIBUTING.md (D-041) only reviews a pull request whose issue is assigned to its author, and GitHub only lets us assign people who have access to the repository.

Here is how we fix it:

  1. Accept the read-access invitation I sent you today. It is at https://github.com/GenAI-Security-Project/agent-control-standard/invitations and in your GitHub notifications. It expires after 7 days.
  2. I assign [RefImpl] Python Guardian sample with FastMCP client instrumentation #135 to you and post here when it's done.
  3. Close this pull request and reopen it, so it counts as opened after the assignment.
  4. Then I review it.

Your issue section already says Closes #135, so you don't need to change the description.

@angelnicolasc

Copy link
Copy Markdown
Collaborator Author

Thanks @rocklambros — just accepted the invitation. Ping me once #135 is assigned and I'll close and reopen the PR right away.

This branch has not been deployed

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

Labels

status:needs-triage Not yet triaged. Applied by the issue forms type:refimpl Reference implementation or adapter work

Projects

Status: In progress

Development

Successfully merging this pull request may close these issues.

[RefImpl] Python Guardian sample with FastMCP client instrumentation

3 participants