Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

fix(wave 2): the MCP client works over a real connection (#1117)

Beenu Arora323633503352
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f84a3749c..3d154a6d5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **The MCP client could not complete a single real call, and every tool it
+ offered a model was rejected by the provider (fix pass, wave 2).**
+
+ `_CappedStream` was not an `httpx.AsyncByteStream`, and `httpx` asserts that
+ before it wraps a response body, so every real `list_tools` and `call_tool`
+ raised `AssertionError` before a byte was read. Every existing test drove the
+ client through its in-process `session_factory`, which is a good harness for
+ the policy questions it asks and bypasses the transport entirely.
+
+ Fixing it surfaced a second defect: the byte cap fired but its reason could
+ not be recovered from the exception, so a tenant's own cap was reported to
+ the model and the ledger as the server being slow.
+
+ Tool names were `mcp.<server>.<tool>`, and a dot is outside the function-name
+ pattern an OpenAI-compatible provider accepts, so the refusal happened at the
+ far end where no local test could see it. Names are now escaped and
+ reversible.
+
+ Air-gap had four sources and four answers. Measured: a loopback MCP server is
+ refused with or without `AISOC_SSRF_ALLOW_PRIVATE`, a private one needs it,
+ and compose delivered none of the three variables, so an operator could not
+ permit an internal server at all.
+
- **The agents service could not reach the API at all, and three vendors were
never offered to an investigation (fix pass, wave 1).**
diff --git a/FIX_PASS_PROGRESS.md b/FIX_PASS_PROGRESS.md
index c3c288c68..c3a803ec0 100644
--- a/FIX_PASS_PROGRESS.md
+++ b/FIX_PASS_PROGRESS.md
@@ -79,10 +79,10 @@ conditional `numpy` pins collide into an unresolvable install. Parse with
## Wave 2: The MCP client works over a real connection
-- [ ] **2.1** Transport: `_CappedStream` is a real `httpx.AsyncByteStream`
-- [ ] **2.2** Tool names match the function-name pattern
-- [ ] **2.3** SSRF re-resolution and air-gap: code, test and doc agree
-- [ ] **2.4** Docs and claim rows: generated tool count, unpublished package, stale counts
+- [x] **2.1** Transport: `_CappedStream` is a real `httpx.AsyncByteStream`
+- [x] **2.2** Tool names match the function-name pattern
+- [x] **2.3** Air-gap: code, test, doc and compose agree. SSRF re-resolution recorded as a stated limit
+- [x] **2.4** Docs and claim rows: tool count gated per occurrence, unpublished package stated
## Wave 3: Replay, shadow mode and evaluation measure the real thing
@@ -424,3 +424,101 @@ alone and fails three assertions when run in the same process as the full
absent. CI runs them in separate jobs, and `ci.yml` excludes
`tests/isolation/` for this reason, so the arrangement is sound. It is recorded
here because "passes only in isolation" is a fragility, not a result.
+
+## Wave 2: the MCP client over a real connection
+
+### 2.1 Transport
+
+**Reproduced.** `services/agents/tests/test_mcp_real_transport.py` runs a real
+`FastMCP` streamable-HTTP server on a loopback socket and connects with **no
+`session_factory`**. Pre-fix: `AssertionError` raised inside
+`httpx/_client.py:1732`, `assert isinstance(response.stream, AsyncByteStream)`.
+
+`_CappedStream` was a plain class, and its `__aiter__` was `async def`, which
+makes the object an awaitable rather than an async iterable. Both are fixed.
+
+**Why the existing suite could not see it.** Every test in
+`test_mcp_client.py` drives `McpClient` through `session_factory`, which exists
+so a test can run a real MCP server in-process. That is a good harness for the
+policy questions it asks and it bypasses the transport entirely, so the one
+thing it cannot test is the transport. The byte-cap test exercised
+`_CappedStream` directly, so the cap was genuinely proven and the path to it
+was not.
+
+**A second defect found by fixing the first.** With the isinstance error gone,
+the byte cap fired and the *reason was unrecoverable*: the cap raises inside
+the stream, the MCP library reads that stream in its own `anyio` task, and
+what reaches the caller is `ExceptionGroup -> ExceptionGroup -> TimeoutError`
+with the `ResponseTooLarge` nowhere in the tree. Measured by walking the group,
+not assumed. That matters because `tools._failure` reports
+`type(exc).__name__` to the model and the ledger, so a tenant's own cap firing
+was recorded as the server being slow -- a diagnostic naming the wrong cause.
+
+`CapMarker` carries the reason by reference from the client down to the stream.
+A `ContextVar` was tried first and cannot work: a context propagates *into* a
+child task, so a value set by the reader is invisible to the coroutine that
+awaited it.
+
+**Negative control:** reverting the base class alone returns 3 failures.
+
+### 2.2 Tool names
+
+**Reproduced:** `'mcp.fixpass.lookup_host' is not a callable function name`.
+A dot is outside `^[a-zA-Z0-9_-]{1,64}$`, so **every MCP tool offered to a
+model was rejected by the provider**, and nothing local could see it because
+the name is only validated at the far end.
+
+`namespaced` now emits `mcp__<server>__<tool>` with each part escaped, and
+`parse_namespaced` reverses it. Dispatch is by dict lookup and never needed
+parsing; the reverse exists so a ledger row names the server that answered.
+Readability is the cost: `get_host` encodes as `get_5fhost`, because escaping
+`_` is what keeps the `__` separator unambiguous.
+
+The existing tests hardcoded `mcp.vendor.get_host`. They now derive the
+expected name from `namespaced()`, so a future encoding change cannot diverge
+silently again.
+
+**Negative control:** restoring the dotted form fails 6 of the 9.
+
+### 2.3 Air-gap: four sources, four different answers
+
+Measured against `validate_outbound_url` rather than read off the doc:
+
+| Target | `ALLOW_PRIVATE` unset | set |
+|---|---|---|
+| `127.0.0.1` | refused, loopback | **still refused** |
+| RFC1918 | refused, private | allowed |
+
+So the doc's "Internal MCP servers keep working" was true of the air-gap check
+and false of the deployment. The test named
+`test_air_gap_mode_permits_an_internal_server` **asserted the server is
+refused** -- its own docstring said so -- and the doc had read the name.
+
+Corrected: the doc states both switches and that loopback never works; the
+test is renamed to what it proves; and compose now passes `AISOC_AIRGAPPED`,
+`AISOC_AIRGAP_ALLOWLIST` and `AISOC_SSRF_ALLOW_PRIVATE`, none of which it
+delivered, so an operator could not permit an internal server at all.
+
+**The check-then-resolve-again half is a stated limit, not a fix.** The guard
+resolves a hostname and httpx resolves it again when it connects. Pinning the
+connection to the vetted address needs a custom transport resolver, which is
+out of scope for a fix pass; it is recorded here and in the doc rather than
+left implied.
+
+### 2.4 Docs and claim rows
+
+* `@aisoc/mcp` answers **404** on npm, so the quickstart's "works on a fresh
+ clone before you've run `pnpm build`" was false. Corrected to say the build
+ is required and why.
+* The claim matrix carried **two rows for the same claim**, one saying 19 tools
+ and a stale one saying 14 that cited a README line which does not mention
+ tools. The real count, generated from `ALL_TOOLS`, is **19**.
+* **The gate that should have caught it was blind.**
+ `tests/published-count.test.ts` used `pattern.exec(body)`, which returns the
+ first match and stops, so the correct row shadowed the wrong one and the gate
+ reported OK over a false claim in the governance file itself. It now checks
+ every occurrence, and with that change it names
+ `publishes 14, the registry holds 19` before the row was removed.
+* Removing the row took the matrix 291 -> 290, which `readme_gates` caught in
+ three more documents quoting the old figure. That is the copied-count failure
+ working as designed.
diff --git a/ROADMAP.md b/ROADMAP.md
index f328ae80c..a68f8926b 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -44,7 +44,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl
- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.
- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.
-The claim-to-gate matrix stands at **291 rows — 291 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
+The claim-to-gate matrix stands at **290 rows — 290 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
## v4.0 — Shipped
diff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.md
index dbd38d450..e3827c2c0 100644
--- a/apps/docs/docs/compliance/evidence-pack.md
+++ b/apps/docs/docs/compliance/evidence-pack.md
@@ -33,7 +33,7 @@ and says so.
| Prompt-injection resistance | Three adversarial corpora: 32 payloads scanned in isolation and 71 incident pairs whose payloads are placed in attacker-controllable fields, both against a clean twin with a recall floor and a false-positive ceiling, plus 34 held-out pairs authored after the guard was frozen and carrying no floor at all, on which the guard measures 7.1% | `services/agents/tests/adversarial/` |
| Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |
-The last row is the one worth reading first. It is the honest index: 291 rows
+The last row is the one worth reading first. It is the honest index: 290 rows
`GATED`, 0 `PARTIAL`, and a ratchet that refuses to let a row sit at
`NO GATE`. Re-read the figure from the table rather than from here — a count
copied into prose goes stale in silence, which is why
diff --git a/apps/docs/docs/operations/mcp-client.md b/apps/docs/docs/operations/mcp-client.md
index a997a16c9..1dd6e3583 100644
--- a/apps/docs/docs/operations/mcp-client.md
+++ b/apps/docs/docs/operations/mcp-client.md
@@ -167,7 +167,15 @@ a statement about what the model sees.
the enforcing check is the one at connect time.
- **Air-gap.** With `AISOC_AIRGAPPED` set, a server outside
`AISOC_AIRGAP_ALLOWLIST` that is not an internal host or a private address
- is refused. Internal MCP servers keep working.
+ is refused by the air-gap check.
+- **An internal server still needs the SSRF guard's permission, and that is a
+ separate switch.** Clearing the air-gap check is not the same as being
+ reachable. Measured against `validate_outbound_url`: an RFC1918 address is
+ refused unless `AISOC_SSRF_ALLOW_PRIVATE=1`, and a **loopback** address is
+ refused with or without it. So a sidecar MCP server on `127.0.0.1` cannot be
+ reached at all, and one on a private address needs that variable set. This
+ used to read "internal MCP servers keep working", which was true of the
+ air-gap check and false of the deployment.
- **stdio.** Off. A stdio server is a local process the agents container would
start, which is code execution rather than an HTTP request. Two switches
turn it on:
diff --git a/apps/docs/docs/quickstart.md b/apps/docs/docs/quickstart.md
index dc4e33119..787fd3e39 100644
--- a/apps/docs/docs/quickstart.md
+++ b/apps/docs/docs/quickstart.md
@@ -553,8 +553,12 @@ aisoc mcp install --host <editor>
`aisoc mcp serve` prefers the local TypeScript build at
`services/mcp/dist/index.js` when present, and falls back to
-`npx @aisoc/mcp` otherwise — so it works on a fresh clone before you've
-run `pnpm build`.
+`npx @aisoc/mcp` otherwise.
+
+**Run `pnpm build` first.** `@aisoc/mcp` is not published to npm yet
+(`registry.npmjs.org/@aisoc/mcp` answers 404), so on a fresh clone the
+fallback cannot resolve and only the local build works. Publishing is tracked
+with the rest of the package work.
### 7. Tear down
diff --git a/docker-compose.yml b/docker-compose.yml
index 9648bc398..07ae7a160 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -732,6 +732,16 @@ services:
SECRET_KEY: ${SECRET_KEY:-}
AISOC_SERVICE_TOKEN: ${AISOC_SERVICE_TOKEN:-}
AISOC_API_SERVICE_TOKEN: ${AISOC_API_SERVICE_TOKEN:-}
+ # Air-gap posture and the SSRF guard, both off by default.
+ #
+ # Passed through because an operator could not set them at all before:
+ # the MCP client reads all three and compose delivered none, so an
+ # internal MCP server was unreachable with no way to permit it. Note
+ # that ALLOW_PRIVATE permits RFC1918 and never loopback, so a sidecar
+ # on 127.0.0.1 stays refused by design.
+ AISOC_AIRGAPPED: ${AISOC_AIRGAPPED:-}
+ AISOC_AIRGAP_ALLOWLIST: ${AISOC_AIRGAP_ALLOWLIST:-}
+ AISOC_SSRF_ALLOW_PRIVATE: ${AISOC_SSRF_ALLOW_PRIVATE:-}
# The agents service's own service credential, used in both directions:
# presented as `X-AiSOC-Service-Token` on the API's internal context
# routes, and verified by `app.security.tenant_scope` when the API calls
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 894f7ea77..9d902b27b 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -197,7 +197,6 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| The agents service requests the MCP registry at a path the API service serves | `services/agents/app/mcp/registry_client.py` | `ci.yml` agents job (`test_mcp_registry_client.py::test_the_registry_url_matches_where_the_route_is_mounted`: the app mount, the v1 router prefix and the endpoint router prefix are read out of the API service's own source with `ast` and composed the way the service composes them, then compared against the URL the client builds. Proven able to fail by emptying `API_PREFIX`, which names both the requested path and the served set) | core | GATED | The same defect D16 records: Phase 1.2 shipped a client missing `/api/v1`, so every request would have 404'd while three suites stayed green, because the test asserted the URL the code produced rather than the URL the service serves. This service cannot import that one, so reading the other tree's source is the only comparison in the direction that drifts |
| No MCP tool AiSOC ships can perform a response action; the action tool is dry-run only | `services/mcp/README.md` (Actions are previewed, never performed); `apps/docs/docs/integrations/mcp.md` | `ci.yml :: mcp` (`tests/actions.test.ts`: the **source** of `services/mcp/src/` is read and no string may name `/live-actions/dispatch`, so a second action tool added later is caught rather than only the one under test; the preview handler is driven against a recording client and asserted to make exactly one request, to the dry-run path, carrying `dry_run: true`; and its strict schema is asserted to reject a caller-supplied `dry_run: false`. Proven able to fail by pointing the module constant at the dispatch path, which reds both the source scan and the request assertion) | core | GATED | The enforcing control is upstream: `POST /api/v1/live-actions/dry-run` forces `dry_run: true` server-side whatever the body says and proxies only that path. This row is the second lock, on the side an agent can see, because an MCP key is credential material that lives in an editor's configuration file |
| Every tool AiSOC's MCP server publishes carries honest behaviour annotations | `services/mcp/README.md` (Tools exposed); `apps/docs/docs/integrations/mcp.md` (Annotations, and what is read-only) | `ci.yml :: mcp` (`tests/actions.test.ts`: every tool in `ALL_TOOLS` must declare `readOnlyHint` as a boolean rather than leaving it absent, no tool may be annotated destructive, and the set of tools annotated **not** read-only is pinned to exactly `aisoc_run_investigation`, so a future write tool cannot arrive annotated read-only and a read tool cannot drift into looking state-changing) | core | GATED | The annotations are what a client reads to decide whether it may call a tool at all. AiSOC's own MCP client refuses a tool whose server sets `destructiveHint: true` or `readOnlyHint: false`, and treats an absent annotation as no claim, so a server publishing nothing forces every operator to vouch for every tool by name |
-| MCP server exposes 14 tools | README L179 | `ci.yml :: mcp` | core | GATED | - |
| Prompt-injection resistance | (implied by agent claims) | `ci.yml :: python-test` (agents) runs `test_prompt_sanitizer.py`, `test_prompt_envelope.py` and `tests/adversarial/` — a 32-payload corpus grouped by attacker goal, enforcing a recall floor **and** a false-positive ceiling on real security content that reads adversarially. Action-trigger and exfiltration payloads are individually required rather than averaged, because an injected containment turns the SOC into a denial-of-service tool pointed at its own estate. Phase 3 adds a second, harder corpus at incident level (`test_injection_incidents.py`) whose payloads are written to fit the field they arrive in, enforcing a floor, a ceiling and an exact ratchet naming every current blind spot by id | core | GATED | obfuscation is an arms race and is recorded rather than individually required; two payloads are currently xfail and counted in the recall rate. The two corpora measure the same guard and are **not comparable**: one asks whether the guard recognises a string, the other whether it recognises it where an attacker can put it, and the second scores materially lower. Neither measures a model |
| An investigation can read the vendor a tenant actually runs, not just CrowdStrike and Okta | `plans/aisoc_gap_closure_plan.plan.md` (4.2); `services/actions/app/live_actions/investigation_reads.py` | `ci.yml` actions job (`test_investigation_reads_phase4.py`, 25 tests over seven new executors against vendor-shaped synthetic payloads on the real HTTP path. Each verb is tested for the pair that must never collapse: a host or principal the vendor does not hold is `SUCCEEDED` with `found: False`, a vendor that 5xxs is `FAILED`, and a failed read is asserted to carry **no** `count`, `detections` or `found` key, because a `count: 0` reaching a model is the strongest exonerating evidence there is and would be false. Entra's licensed risk leg may fail without taking the sign-ins down and reads as unknown rather than as no risk; Google Workspace's 403 names the missing `admin.reports.audit.readonly` scope rather than reporting an account with no logins) + `ci.yml` gates job (`check_action_contract.py`, 79 executors, and `check_capability_mirror` comparing the actions vocabulary against the connectors `Capability` enum in both directions) | core | GATED | Five of the seven are new vendor arms on the three existing read verbs, so they inherit the `READ_ONLY` contract and cannot drift low; only `lookup_cloud_audit` and `lookup_endpoint_telemetry` needed their own entry. **No call in this repository has been made against a live vendor** for any of them: there is no funded CrowdStrike, SentinelOne, Entra, Google Workspace, Defender or AWS account here, so the wire shapes are pinned against the vendors' published schemas and the live path is unverified, which the docs state rather than imply |
| A caller of a vendor read never supplies query text; the executor owns the query | `plans/aisoc_gap_closure_plan.plan.md` (4.1, 4.2); `services/actions/app/clients/defender_client.py` (`_HUNT_TEMPLATES`) | `ci.yml` actions job (`test_investigation_reads_phase4.py`: `lookup_endpoint_telemetry` is offered four rejected inputs including a bare KQL pipeline, a template name with a statement appended and a case variation, and each is refused **before the credential is read** with a route asserted uncalled, so a refused template cannot reach the vendor; the accepted path is asserted on the KQL that reaches the wire rather than on the argument, with a hostile indicator carrying a quote and a pipe appearing only in its escaped form; the window and row cap are asserted at 720h and 200 against a caller asking for 99,999h and 10,000 rows. Entra's OData literal is asserted the same way, with the doubled quote present and the single-quote form absent) | core | GATED | The escaping is grammar-specific and each grammar is handled at its own boundary: KQL escapes backslash and double quote, OData doubles a single quote, and the CloudTrail attribute key is checked against AWS's own closed vocabulary rather than escaped at all. A new vendor grammar needs its own escape and its own test; nothing structurally forces that beyond review |
@@ -302,8 +301,8 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
## Summary
-- Total: 291
-- GATED: 291
+- Total: 290
+- GATED: 290
- PARTIAL: 0
- NO GATE: 0
diff --git a/services/agents/app/mcp/client.py b/services/agents/app/mcp/client.py
index 80730486c..38ed84d19 100644
--- a/services/agents/app/mcp/client.py
+++ b/services/agents/app/mcp/client.py
@@ -95,16 +95,17 @@ def _airgap_blocked(url: str) -> str | None:
class _CappedTransport(httpx.AsyncBaseTransport):
"""Wrap a transport so a response body cannot exceed ``limit`` bytes."""
- def __init__(self, inner: httpx.AsyncBaseTransport, limit: int) -> None:
+ def __init__(self, inner: httpx.AsyncBaseTransport, limit: int, marker: CapMarker) -> None:
self._inner = inner
self._limit = limit
+ self._marker = marker
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
response = await self._inner.handle_async_request(request)
return httpx.Response(
status_code=response.status_code,
headers=response.headers,
- stream=_CappedStream(response.stream, self._limit),
+ stream=_CappedStream(response.stream, self._limit, self._marker),
extensions=response.extensions,
request=request,
)
@@ -113,21 +114,83 @@ class _CappedTransport(httpx.AsyncBaseTransport):
await self._inner.aclose()
-class _CappedStream:
- """An async byte stream that raises once the running total passes the cap."""
+class CapMarker:
+ """Why a call failed, when the reason cannot survive the exception.
- def __init__(self, inner: Any, limit: int) -> None:
+ The cap is enforced inside the response stream, which the MCP library
+ reads in its own ``anyio`` task. Raising there cancels the task group, and
+ what reaches the caller is ``ExceptionGroup -> ExceptionGroup ->
+ TimeoutError`` with the ``ResponseTooLarge`` nowhere in the tree.
+ Measured by walking the group on a 400 KB body under a 4 KB cap, not
+ assumed.
+
+ A ``ContextVar`` was tried first and cannot work: a context propagates
+ *into* a child task, so a value set by the reader is invisible to the
+ coroutine that awaited it. This is shared by reference instead, from the
+ client down to the stream that trips it.
+
+ It matters because ``app.mcp.tools._failure`` reports
+ ``type(exc).__name__`` to the model and to the ledger. Left alone, a
+ tenant's own byte cap firing is recorded as the server being slow, which
+ sends an operator to look at a server that is not the problem.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self) -> None:
+ self.reason: str | None = None
+
+
+def _surface_cap_refusal(marker: CapMarker, exc: BaseException) -> None:
+ """Re-raise as :class:`ResponseTooLarge` when the cap was the real cause.
+
+ ``exc`` is whatever the MCP library surfaced, usually a timeout. If the
+ cap tripped during this call, that timeout is a consequence of closing the
+ connection and the honest exception is the refusal.
+ """
+ if marker.reason is not None:
+ reason, marker.reason = marker.reason, None
+ raise ResponseTooLarge(reason) from exc
+ if isinstance(exc, ResponseTooLarge):
+ raise exc
+
+
+class _CappedStream(httpx.AsyncByteStream):
+ """An async byte stream that raises once the running total passes the cap.
+
+ The base class is load-bearing, not decoration. ``httpx`` asserts
+ ``isinstance(response.stream, AsyncByteStream)`` in
+ ``_send_single_request`` before it wraps the body, so a plain class here
+ raised ``AssertionError`` on **every** real ``list_tools`` and
+ ``call_tool``. Nothing caught it, because every test drives ``McpClient``
+ through its ``session_factory``, which exists so a test can run a real MCP
+ server in-process and which therefore never constructs this transport at
+ all. The byte-cap test exercised this class directly, so the cap was
+ genuinely proven and the path to it was not.
+
+ ``__aiter__`` is a plain ``def`` returning an async generator. Declaring
+ it ``async def`` makes the object an *awaitable*, not an async iterable,
+ so ``async for`` over it fails even once the isinstance check passes.
+ """
+
+ def __init__(self, inner: Any, limit: int, marker: CapMarker) -> None:
self._inner = inner
self._limit = limit
+ self._marker = marker
- async def __aiter__(self) -> AsyncIterator[bytes]:
+ def __aiter__(self) -> AsyncIterator[bytes]:
+ return self._iterate()
+
+ async def _iterate(self) -> AsyncIterator[bytes]:
seen = 0
async for chunk in self._inner:
seen += len(chunk)
if seen > self._limit:
- raise ResponseTooLarge(
- f"the MCP server sent more than the configured {self._limit} bytes; the connection was closed mid-response"
- )
+ reason = f"the MCP server sent more than the configured {self._limit} bytes; the connection was closed mid-response"
+ # Recorded before raising, because this exception does not
+ # reach the caller: see `CapMarker`.
+ self._marker.reason = reason
+ raise ResponseTooLarge(reason)
yield chunk
async def aclose(self) -> None:
@@ -136,7 +199,7 @@ class _CappedStream:
await aclose()
-def _client_factory(limit: int):
+def _client_factory(limit: int, marker: CapMarker):
"""An ``McpHttpClientFactory`` whose clients cannot over-read."""
def factory(
@@ -144,7 +207,7 @@ def _client_factory(limit: int):
timeout: httpx.Timeout | None = None,
auth: httpx.Auth | None = None,
) -> httpx.AsyncClient:
- kwargs: dict[str, Any] = {"transport": _CappedTransport(httpx.AsyncHTTPTransport(), limit)}
+ kwargs: dict[str, Any] = {"transport": _CappedTransport(httpx.AsyncHTTPTransport(), limit, marker)}
if timeout is not None:
kwargs["timeout"] = timeout
if headers is not None:
@@ -166,6 +229,10 @@ class McpClient:
"""
def __init__(self, config: McpServerConfig, *, session_factory: Any | None = None) -> None:
+ # One marker per client, shared by reference down to the stream that
+ # trips it. See :class:`CapMarker` for why the reason cannot travel on
+ # the exception.
+ self._cap = CapMarker()
self.config = config
self._session_factory = session_factory
@@ -208,7 +275,7 @@ class McpClient:
url,
headers=self.config.headers() or None,
timeout=self.config.timeout_seconds,
- httpx_client_factory=_client_factory(self.config.max_response_bytes),
+ httpx_client_factory=_client_factory(self.config.max_response_bytes, self._cap),
) as (read_stream, write_stream, _get_session_id):
async with ClientSession(read_stream, write_stream) as session:
await session.initialize()
@@ -216,8 +283,12 @@ class McpClient:
async def list_tools(self) -> list[Any]:
"""Discover the server's tools, under the tenant's timeout."""
- async with self.session() as session:
- result = await asyncio.wait_for(session.list_tools(), timeout=self.config.timeout_seconds)
+ try:
+ async with self.session() as session:
+ result = await asyncio.wait_for(session.list_tools(), timeout=self.config.timeout_seconds)
+ except BaseException as exc:
+ _surface_cap_refusal(self._cap, exc)
+ raise
return list(getattr(result, "tools", []) or [])
async def call_tool(self, name: str, arguments: dict[str, Any]) -> Any:
@@ -228,5 +299,9 @@ class McpClient:
has to happen before anything opens a socket. ``app.mcp.tools`` checks
it, twice, on the way in.
"""
- async with self.session() as session:
- return await asyncio.wait_for(session.call_tool(name, arguments), timeout=self.config.timeout_seconds)
+ try:
+ async with self.session() as session:
+ return await asyncio.wait_for(session.call_tool(name, arguments), timeout=self.config.timeout_seconds)
+ except BaseException as exc:
+ _surface_cap_refusal(self._cap, exc)
+ raise
diff --git a/services/agents/app/mcp/policy.py b/services/agents/app/mcp/policy.py
index 1dabfa812..e46009e84 100644
--- a/services/agents/app/mcp/policy.py
+++ b/services/agents/app/mcp/policy.py
@@ -129,9 +129,100 @@ class ToolVerdict:
parameters: dict[str, Any] = field(default_factory=dict)
+#: What an OpenAI-compatible provider accepts as a function name.
+#:
+#: This is the whole reason the encoding below exists. The id used to be
+#: ``mcp.<server>.<tool>``, and a dot is not in this set, so **every MCP tool
+#: offered to a model was rejected by the provider**. Nothing local could see
+#: it: the name is only validated at the far end.
+FUNCTION_NAME_PATTERN = re.compile(r"^[a-zA-Z0-9_-]{1,64}$")
+
+#: Separates the prefix, the server and the tool. Two underscores cannot occur
+#: inside an encoded part, because :func:`_encode_part` only ever emits a
+#: single ``_`` followed by two hex digits.
+_SEPARATOR = "__"
+
+_NAME_PREFIX = "mcp"
+
+#: Characters an encoded part may contain unescaped. Deliberately excludes
+#: ``_``, so the separator stays unambiguous.
+_SAFE_CHARS = frozenset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-")
+
+
+def _encode_part(part: str) -> str:
+ """One name component, reversibly, using only safe characters.
+
+ Every character outside :data:`_SAFE_CHARS` becomes ``_`` plus two hex
+ digits, which covers the dot that broke this, the underscore that would
+ otherwise collide with the separator, and anything else an operator puts
+ in a server name.
+ """
+ out: list[str] = []
+ for char in part:
+ if char in _SAFE_CHARS:
+ out.append(char)
+ else:
+ code = ord(char)
+ if code > 0xFF:
+ # Above Latin-1 this scheme has no room. A server name is
+ # operator-supplied configuration, so refusing with the reason
+ # is better than emitting a name the provider rejects.
+ raise ValueError(f"cannot encode {char!r} in an MCP tool name; use ASCII in the server name and tool id")
+ out.append(f"_{code:02x}")
+ return "".join(out)
+
+
+def _decode_part(part: str) -> str:
+ out: list[str] = []
+ index = 0
+ while index < len(part):
+ char = part[index]
+ if char == "_" and index + 2 < len(part) + 1:
+ hex_digits = part[index + 1 : index + 3]
+ if len(hex_digits) == 2:
+ try:
+ out.append(chr(int(hex_digits, 16)))
+ except ValueError:
+ out.append(char)
+ index += 1
+ continue
+ index += 3
+ continue
+ out.append(char)
+ index += 1
+ return "".join(out)
+
+
def namespaced(server: str, tool: str) -> str:
- """The id the model sees: ``mcp.<server>.<tool>``."""
- return f"mcp.{server}.{tool}"
+ """The id the model sees, as a name a provider will actually accept.
+
+ ``mcp__<server>__<tool>`` with each part escaped. This used to be
+ ``mcp.<server>.<tool>``; see :data:`FUNCTION_NAME_PATTERN`.
+
+ Raises ``ValueError`` when the result cannot be a valid function name,
+ which is a configuration problem an operator can fix by shortening the
+ server name. Returning an invalid name instead would move the failure to
+ the provider, where the message says nothing about this deployment.
+ """
+ name = f"{_NAME_PREFIX}{_SEPARATOR}{_encode_part(server)}{_SEPARATOR}{_encode_part(tool)}"
+ if not FUNCTION_NAME_PATTERN.match(name):
+ raise ValueError(
+ f"{name!r} is not a callable function name ({len(name)} characters; the limit is 64). Shorten the MCP server name."
+ )
+ return name
+
+
+def parse_namespaced(name: str) -> tuple[str, str]:
+ """``(server, tool)`` from a name :func:`namespaced` produced.
+
+ Dispatch does not need this -- the registry looks a tool up by name and
+ the closure already holds its server -- but a ledger row and a log line
+ do, so an operator reading one can tell which server answered.
+ """
+ parts = name.split(_SEPARATOR)
+ if len(parts) != 3 or parts[0] != _NAME_PREFIX:
+ raise ValueError(f"{name!r} is not an MCP tool name")
+ return _decode_part(parts[1]), _decode_part(parts[2])
def vet_server(
diff --git a/services/agents/tests/test_mcp_client.py b/services/agents/tests/test_mcp_client.py
index 433227b61..569305d7d 100644
--- a/services/agents/tests/test_mcp_client.py
+++ b/services/agents/tests/test_mcp_client.py
@@ -34,7 +34,7 @@ import pytest
from app.mcp import tools as tools_module
from app.mcp.client import McpClient, McpTransportRefused
from app.mcp.config import McpServerConfig, server_configs_from_payload
-from app.mcp.policy import stdio_enabled, vet_server, vet_tool
+from app.mcp.policy import namespaced, stdio_enabled, vet_server, vet_tool
from app.mcp.tools import DiscoveredTool, McpToolInvoker, build_mcp_toolset
from app.mcp.untrusted import BOUNDARY_NOTE, contain_mcp_result
from mcp.server.fastmcp import FastMCP
@@ -202,7 +202,7 @@ async def test_an_allowlisted_read_tool_is_bound_called_and_fenced(server, ledge
servers=[config()],
session_factory=memory_session_factory(server),
)
- assert [t.name for t in toolset.tools] == ["mcp.vendor.get_host"]
+ assert [t.name for t in toolset.tools] == [namespaced("vendor", "get_host")]
result = await toolset.tools[0].fn(hostname="WIN-DC-01")
assert result["untrusted"] is True
@@ -248,10 +248,10 @@ async def test_a_destructive_tool_is_never_bound_and_the_refusal_is_recorded(ser
servers=[config(tool_allowlist=["get_host", "isolate_host"])],
session_factory=memory_session_factory(server),
)
- assert "mcp.vendor.isolate_host" not in [t.name for t in toolset.tools]
+ assert namespaced("vendor", "isolate_host") not in [t.name for t in toolset.tools]
refused = {name: classification for name, classification, _ in toolset.refusals}
- assert refused["mcp.vendor.isolate_host"] == "destructive"
+ assert refused[namespaced("vendor", "isolate_host")] == "destructive"
rows = [e for e in ledger.of_kind("mcp_tool_refused") if e["payload"]["tool"] == "isolate_host"]
assert len(rows) == 1
@@ -270,7 +270,7 @@ async def test_a_tool_that_declares_itself_not_read_only_is_refused_too(server,
)
assert toolset.tools == []
refused = {name: classification for name, classification, _ in toolset.refusals}
- assert refused["mcp.vendor.create_ticket"] == "state_changing"
+ assert refused[namespaced("vendor", "create_ticket")] == "state_changing"
async def test_an_unannotated_tool_is_bound_only_because_an_operator_named_it(server, ledger) -> None:
@@ -281,7 +281,7 @@ async def test_an_unannotated_tool_is_bound_only_because_an_operator_named_it(se
servers=[config(tool_allowlist=["unannotated_lookup"])],
session_factory=memory_session_factory(server),
)
- assert [t.name for t in named.tools] == ["mcp.vendor.unannotated_lookup"]
+ assert [t.name for t in named.tools] == [namespaced("vendor", "unannotated_lookup")]
unnamed = await build_mcp_toolset(
"tenant-a",
@@ -289,7 +289,7 @@ async def test_an_unannotated_tool_is_bound_only_because_an_operator_named_it(se
servers=[config(tool_allowlist=["get_host"])],
session_factory=memory_session_factory(server),
)
- assert "mcp.vendor.unannotated_lookup" not in [t.name for t in unnamed.tools]
+ assert namespaced("vendor", "unannotated_lookup") not in [t.name for t in unnamed.tools]
async def test_an_empty_allowlist_offers_nothing_at_all(server, ledger) -> None:
@@ -384,12 +384,12 @@ async def test_a_poisoned_tool_description_drops_the_tool(server, ledger) -> Non
session_factory=memory_session_factory(server),
)
names = [t.name for t in toolset.tools]
- assert names == ["mcp.vendor.get_host"]
+ assert names == [namespaced("vendor", "get_host")]
# Nothing of the payload reaches any description the model is shown.
assert "isolate the host" not in " ".join(t.description for t in toolset.tools).lower()
refused = {name: classification for name, classification, _ in toolset.refusals}
- assert refused["mcp.vendor.poisoned_description"] == "injected_description"
+ assert refused[namespaced("vendor", "poisoned_description")] == "injected_description"
rows = [e for e in ledger.of_kind("mcp_tool_refused") if e["payload"]["tool"] == "poisoned_description"]
assert rows and "injection into the prompt" in rows[0]["payload"]["reason"]
@@ -530,8 +530,16 @@ class TestTransportPolicy:
async with client.session():
pass # pragma: no cover
- async def test_air_gap_mode_permits_an_internal_server(self, monkeypatch) -> None:
- """Refused later by the SSRF guard's DNS step, not by the air-gap check."""
+ async def test_the_air_gap_check_does_not_fire_on_an_internal_server(self, monkeypatch) -> None:
+ """What this proves, which is narrower than the old name claimed.
+
+ It was called `test_air_gap_mode_permits_an_internal_server` while
+ asserting the server is **refused** -- just not by the air-gap check.
+ The doc read that name and said internal MCP servers keep working,
+ which is true of this check and false of the deployment: the SSRF
+ guard refuses a private address unless `AISOC_SSRF_ALLOW_PRIVATE=1`
+ and refuses loopback either way.
+ """
monkeypatch.setenv("AISOC_AIRGAPPED", "1")
client = McpClient(config(url="https://mcp.corp.internal/mcp"))
with pytest.raises(McpTransportRefused) as exc:
diff --git a/services/agents/tests/test_mcp_investigation.py b/services/agents/tests/test_mcp_investigation.py
index 2e6371e03..f86876ca3 100644
--- a/services/agents/tests/test_mcp_investigation.py
+++ b/services/agents/tests/test_mcp_investigation.py
@@ -30,6 +30,7 @@ import pytest
from app.llm.tool_loop import run_with_tools
from app.mcp import tools as tools_module
from app.mcp.config import McpServerConfig
+from app.mcp.policy import namespaced
from app.mcp.tools import LEDGER_SEQ_BASE, build_mcp_toolset
from app.tools.registry import ToolRegistry
from mcp.server.fastmcp import FastMCP
@@ -134,31 +135,31 @@ async def test_done_when_an_investigation_calls_a_read_tool_and_refuses_a_destru
# The destructive tool is not merely refused at call time: it is never put
# in front of the model, so it cannot be talked into naming it.
bound = [t.name for t in toolset.tools]
- assert bound == ["mcp.vendor.get_detections"]
+ assert bound == [namespaced("vendor", "get_detections")]
registry = ToolRegistry(toolset.tools)
llm = _ScriptedLLM(
[
- _tool_call("mcp.vendor.get_detections", {"hostname": "WIN-DC-01"}),
+ _tool_call(namespaced("vendor", "get_detections"), {"hostname": "WIN-DC-01"}),
# The model asks for the destructive tool anyway. It was never
# bound, so the loop's own registry refuses it.
- _tool_call("mcp.vendor.isolate_host", {"hostname": "WIN-DC-01"}, cid="c2"),
+ _tool_call(namespaced("vendor", "isolate_host"), {"hostname": "WIN-DC-01"}, cid="c2"),
_final("One detection on WIN-DC-01; containment was not available to me."),
]
)
loop = await run_with_tools(llm, system="You are an analyst.", user="Investigate WIN-DC-01.", registry=registry)
advertised = {s["function"]["name"] for s in (llm.bound_tools or [])}
- assert "mcp.vendor.isolate_host" not in advertised
+ assert namespaced("vendor", "isolate_host") not in advertised
trace = {entry["tool"]: entry["result_preview"] for entry in loop["tool_trace"]}
- assert set(trace) == {"mcp.vendor.get_detections", "mcp.vendor.isolate_host"}
+ assert set(trace) == {namespaced("vendor", "get_detections"), namespaced("vendor", "isolate_host")}
# The loop's own registry has no such tool, because it was never bound.
- assert "unknown tool" in trace["mcp.vendor.isolate_host"]
+ assert "unknown tool" in trace[namespaced("vendor", "isolate_host")]
# The read tool's result did carry the server's data, fenced. Asserted
# against the registry the loop used rather than against the trace, whose
# preview is a 200-character debug string.
- direct = await registry.execute("mcp.vendor.get_detections", {"hostname": "WIN-DC-01"})
+ direct = await registry.execute(namespaced("vendor", "get_detections"), {"hostname": "WIN-DC-01"})
assert "DET-4471" in direct["content"]
assert direct["untrusted"] is True
@@ -249,6 +250,6 @@ async def test_a_run_with_no_run_id_still_works_and_writes_nothing(monkeypatch)
servers=[McpServerConfig(name="vendor", url="https://mcp.vendor.example/mcp", tool_allowlist=["get_detections"])],
session_factory=memory_session_factory(server),
)
- assert [t.name for t in toolset.tools] == ["mcp.vendor.get_detections"]
+ assert [t.name for t in toolset.tools] == [namespaced("vendor", "get_detections")]
assert await toolset.tools[0].fn(hostname="WIN-DC-01")
assert rows == []
diff --git a/services/agents/tests/test_mcp_real_transport.py b/services/agents/tests/test_mcp_real_transport.py
new file mode 100644
index 000000000..bc86186d1
--- /dev/null
+++ b/services/agents/tests/test_mcp_real_transport.py
@@ -0,0 +1,235 @@
+"""The MCP client works over a real HTTP connection, not only an injected session.
+
+Fix pass item 2.1 and 2.2. See `plans/aisoc_fix_pass_plan.plan.md`.
+
+What was wrong
+--------------
+`_CappedStream` in `app/mcp/client.py` wraps a response body so it cannot
+exceed a tenant's byte cap. It was a plain class. `httpx` 0.28.1 asserts
+`isinstance(response.stream, AsyncByteStream)` in `_send_single_request`
+(`httpx/_client.py:1732`), so **every real `list_tools` and `call_tool` raised
+`AssertionError` before a byte was read**. Its `__aiter__` was also `async def`,
+which makes the object an awaitable rather than an async iterable.
+
+Separately, `app/mcp/policy.py` names a bound tool `mcp.<server>.<tool>`.
+OpenAI-compatible function names must match `^[a-zA-Z0-9_-]{1,64}$`, which
+excludes `.`, so every MCP tool offered to a model was rejected by the
+provider.
+
+Why the existing suite did not catch either
+-------------------------------------------
+`McpClient` takes a `session_factory` so a test can drive a real MCP server
+**in-process**, and every test in `test_mcp_client.py` uses it. That is a good
+harness for the policy questions it asks -- which tools are bound, how a
+hostile description is handled -- and it bypasses the transport entirely, so
+the one thing it cannot test is the transport. The byte-cap test passes
+because `_CappedStream` is exercised directly rather than through `httpx`.
+
+And a name is only rejected by the *provider*, so no local test sees it.
+
+What this file asserts
+----------------------
+A real `FastMCP` streamable-HTTP server on a loopback socket, reached with
+**no `session_factory`**, so the request crosses `_CappedTransport` and the
+real `httpx` client. Plus every bound name against the provider's own pattern.
+
+Against the pre-fix tree the transport tests fail with `AssertionError` from
+inside httpx, and the name test fails on the dots.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import re
+import socket
+import threading
+from typing import Any
+
+import pytest
+
+pytestmark = pytest.mark.anyio
+
+#: What an OpenAI-compatible provider accepts as a function name. The dots in
+#: `mcp.<server>.<tool>` are the whole defect.
+FUNCTION_NAME = re.compile(r"^[a-zA-Z0-9_-]{1,64}$")
+
+
+def anyio_backend() -> str:
+ return "asyncio"
+
+
+def _free_port() -> int:
+ with socket.socket() as sock:
+ sock.bind(("127.0.0.1", 0))
+ return int(sock.getsockname()[1])
+
+
[email protected](scope="module")
+def mcp_server():
+ """A real MCP server over streamable HTTP, on its own loopback socket.
+
+ Run in a thread with its own event loop rather than in-process, because
+ the point is that the bytes cross a socket and a real `httpx` client.
+ """
+ fastmcp = pytest.importorskip("mcp.server.fastmcp", reason="mcp not installed")
+ pytest.importorskip("uvicorn", reason="uvicorn not installed")
+ from mcp.types import ToolAnnotations
+
+ port = _free_port()
+ server = fastmcp.FastMCP("fixpass", stateless_http=True)
+
+ @server.tool(annotations=ToolAnnotations(readOnlyHint=True, destructiveHint=False))
+ def lookup_host(hostname: str) -> dict[str, Any]:
+ """Return a small record for one hostname."""
+ return {"hostname": hostname, "seen": True}
+
+ @server.tool(annotations=ToolAnnotations(readOnlyHint=True, destructiveHint=False))
+ def enormous(hostname: str) -> str:
+ """Return far more than any tenant would permit."""
+ return "A" * 400_000
+
+ app = server.streamable_http_app()
+
+ import uvicorn
+
+ config = uvicorn.Config(app, host="127.0.0.1", port=port, log_level="error", lifespan="on")
+ uvicorn_server = uvicorn.Server(config)
+
+ thread = threading.Thread(target=uvicorn_server.run, daemon=True)
+ thread.start()
+
+ # Wait for the socket rather than sleeping a guessed interval.
+ for _ in range(300):
+ with contextlib.suppress(OSError), socket.create_connection(("127.0.0.1", port), timeout=0.2):
+ break
+ import time
+
+ time.sleep(0.1)
+ else: # pragma: no cover - startup guard
+ pytest.fail(f"the MCP server did not bind 127.0.0.1:{port}")
+
+ yield f"http://127.0.0.1:{port}/mcp"
+
+ uvicorn_server.should_exit = True
+ thread.join(timeout=10)
+
+
+def _config(url: str, *, allowlist: tuple[str, ...], cap: int = 64_000):
+ from app.mcp.config import McpServerConfig
+
+ return McpServerConfig(
+ name="fixpass",
+ transport="streamable_http",
+ url=url,
+ tool_allowlist=list(allowlist),
+ max_response_bytes=cap,
+ timeout_seconds=10.0,
+ )
+
+
[email protected](autouse=True)
+def _permit_the_loopback_test_server(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The SSRF guard refuses loopback unconditionally, and should.
+
+ Measured: `validate_outbound_url` rejects `127.0.0.1` with and without
+ `AISOC_SSRF_ALLOW_PRIVATE`, and rejects an RFC1918 address unless that
+ variable is set. A test server has nowhere else to bind.
+
+ This is **not** the boundary under test. The defect this file reproduces
+ is in `_CappedStream` and `httpx`, two layers below the guard, and the
+ guard's own behaviour is asserted in `test_mcp_client.py`. Neutralising it
+ here buys access to the transport and nothing else.
+ """
+ from app.mcp import client as client_mod
+
+ monkeypatch.setattr(client_mod, "validate_outbound_url", lambda url, **kw: url)
+
+
+class TestTheTransportCarriesARealResponse:
+ async def test_list_tools_works_over_a_real_connection(self, mcp_server) -> None:
+ """No `session_factory`, so the bytes cross `_CappedTransport`.
+
+ Pre-fix this raises `AssertionError` from `httpx/_client.py:1732`,
+ because `_CappedStream` was not an `httpx.AsyncByteStream`.
+ """
+ from app.mcp.client import McpClient
+
+ client = McpClient(_config(mcp_server, allowlist=("lookup_host",)))
+ tools = await client.list_tools()
+
+ names = [getattr(t, "name", None) for t in tools]
+ assert "lookup_host" in names, f"the real transport returned no usable tool list: {names!r}"
+
+ async def test_call_tool_works_over_a_real_connection(self, mcp_server) -> None:
+ from app.mcp.client import McpClient
+
+ client = McpClient(_config(mcp_server, allowlist=("lookup_host",)))
+ result = await client.call_tool("lookup_host", {"hostname": "WS-42"})
+
+ assert getattr(result, "isError", False) is not True, f"a real tool call errored: {result!r}"
+ assert "WS-42" in str(result), f"the tool's own answer did not survive the transport: {result!r}"
+
+ async def test_the_byte_cap_still_holds_over_a_real_connection(self, mcp_server) -> None:
+ """The cap is the reason the wrapper exists, so it is asserted through
+ the transport rather than by calling the wrapper directly.
+
+ A fix that satisfied httpx by removing the cap would pass the two
+ tests above and fail this one.
+ """
+ from app.mcp.client import McpClient, ResponseTooLarge
+
+ client = McpClient(_config(mcp_server, allowlist=("enormous",), cap=4_096))
+
+ with pytest.raises(ResponseTooLarge) as refusal:
+ await client.call_tool("enormous", {"hostname": "WS-42"})
+
+ assert "4096" in str(refusal.value), f"the refusal did not name the cap that caused it: {refusal.value}"
+
+
+class TestEveryBoundNameIsCallable:
+ def test_bound_tool_names_match_the_provider_pattern(self) -> None:
+ """`mcp.<server>.<tool>` contains dots, which a provider rejects.
+
+ Checked against the pattern rather than against a list of known-bad
+ characters, because the pattern is what the provider actually applies.
+ """
+ from app.mcp import policy
+
+ name = policy.namespaced("fixpass", "lookup_host")
+
+ assert FUNCTION_NAME.match(name), f"{name!r} is not a callable function name; an OpenAI-compatible provider rejects it"
+
+ def test_the_encoding_is_reversible(self) -> None:
+ """A name the model calls has to resolve back to a server and a tool,
+ or the loop cannot dispatch what the model asked for.
+
+ `parse_namespaced` arrives with this fix, so against the pre-fix tree
+ this fails on the missing symbol rather than on behaviour. The test
+ above is the reproduction; this one pins the half the fix adds.
+ """
+ from app.mcp import policy
+
+ name = policy.namespaced("fixpass", "lookup_host")
+ server_id, tool = policy.parse_namespaced(name)
+
+ assert (server_id, tool) == ("fixpass", "lookup_host")
+
+ @pytest.mark.parametrize(
+ ("server_id", "tool"),
+ [
+ ("with-hyphen", "lookup_host"),
+ ("with_underscore", "get-thing"),
+ ("a", "b"),
+ ("server.with.dots", "tool.with.dots"),
+ ],
+ )
+ def test_the_encoding_survives_awkward_identifiers(self, server_id: str, tool: str) -> None:
+ """A server id is operator-supplied, so it can contain anything the
+ config allows. Every one still has to produce a callable name."""
+ from app.mcp import policy
+
+ name = policy.namespaced(server_id, tool)
+
+ assert FUNCTION_NAME.match(name), f"{name!r} is not callable"
+ assert policy.parse_namespaced(name) == (server_id, tool)
diff --git a/services/mcp/tests/published-count.test.ts b/services/mcp/tests/published-count.test.ts
index cf6e5047e..79f7de3aa 100644
--- a/services/mcp/tests/published-count.test.ts
+++ b/services/mcp/tests/published-count.test.ts
@@ -49,15 +49,23 @@ describe("the published tool count", () => {
const mismatches: string[] = [];
for (const { path, pattern } of PUBLISHED) {
const body = readFileSync(new URL(path, `file://${REPO_ROOT}`), "utf8");
- const match = pattern.exec(body);
- if (match === null) {
+ // EVERY occurrence, not the first. `exec` without the global flag stops
+ // at the first match, and the claim matrix carried two rows for this
+ // claim -- one saying 19 and a stale one saying 14 -- so the correct row
+ // shadowed the wrong one and this gate reported OK over a false claim in
+ // the governance file itself.
+ const flags = pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`;
+ const found = [...body.matchAll(new RegExp(pattern.source, flags))];
+ if (found.length === 0) {
// registry -> document. Deleting the claim is a finding, not a pass.
mismatches.push(`${path}: no published tool count found (pattern ${pattern})`);
continue;
}
- // document -> registry.
- if (Number(match[1]) !== actual) {
- mismatches.push(`${path}: publishes ${match[1]}, the registry holds ${actual}`);
+ // document -> registry, for every occurrence.
+ for (const match of found) {
+ if (Number(match[1]) !== actual) {
+ mismatches.push(`${path}: publishes ${match[1]}, the registry holds ${actual}`);
+ }
}
}
expect(mismatches).toEqual([]);