From ace7bf6d2d7287129cc525d0156708002451e1e1 Mon Sep 17 00:00:00 2001 From: tercel Date: Sat, 28 Nov 2026 02:21:56 +0800 Subject: [PATCH 1/5] feat(mcp): apply caller-aware discovery to tools and docs Signed-off-by: tercel --- .github/workflows/core-candidate.yml | 6 +- .github/workflows/python.yml | 2 +- .github/workflows/rust.yml | 6 +- .github/workflows/typescript.yml | 2 +- a2a/python/pyproject.toml | 2 +- a2a/rust/Cargo.lock | 4 +- a2a/rust/Cargo.toml | 2 +- a2a/typescript/package.json | 2 +- a2a/typescript/pnpm-lock.yaml | 12 +- cli/python/pyproject.toml | 2 +- cli/rust/Cargo.lock | 4 +- cli/rust/Cargo.toml | 2 +- cli/typescript/package.json | 4 +- cli/typescript/pnpm-lock.yaml | 12 +- mcp/conformance/fixtures/system_surface.json | 9 +- mcp/docs/index.md | 1 + mcp/python/pyproject.toml | 2 +- mcp/python/src/apcore_mcp/apcore_mcp.py | 6 +- mcp/python/src/apcore_mcp/server/factory.py | 60 ++++- mcp/python/src/apcore_mcp/server/router.py | 19 +- .../tests/server/test_capability_discovery.py | 121 ++++++++++ mcp/python/tests/test_api.py | 6 +- mcp/python/tests/test_management_surfaces.py | 6 +- mcp/python/tests/test_serve_params.py | 10 +- .../tests/test_system_surface_conformance.py | 6 +- mcp/rust/Cargo.lock | 4 +- mcp/rust/Cargo.toml | 2 +- mcp/rust/src/apcore_mcp.rs | 216 ++++++++++++++++++ mcp/rust/src/server/factory.rs | 185 +++++++++------ mcp/rust/src/server/router.rs | 45 ++++ mcp/rust/src/server/transport.rs | 155 +++++++++---- mcp/typescript/README.md | 7 + mcp/typescript/package.json | 2 +- mcp/typescript/pnpm-lock.yaml | 12 +- mcp/typescript/src/server/factory.ts | 51 ++++- mcp/typescript/src/server/router.ts | 11 +- mcp/typescript/src/types.ts | 2 + .../tests/server/capability-discovery.test.ts | 111 +++++++++ toolkit/python/pyproject.toml | 2 +- toolkit/rust/Cargo.lock | 4 +- toolkit/rust/Cargo.toml | 2 +- toolkit/typescript/package.json | 2 +- toolkit/typescript/pnpm-lock.yaml | 2 +- 43 files changed, 936 insertions(+), 187 deletions(-) create mode 100644 mcp/python/tests/server/test_capability_discovery.py create mode 100644 mcp/typescript/tests/server/capability-discovery.test.ts diff --git a/.github/workflows/core-candidate.yml b/.github/workflows/core-candidate.yml index 4b90105a..3bb93b27 100644 --- a/.github/workflows/core-candidate.yml +++ b/.github/workflows/core-candidate.yml @@ -201,7 +201,7 @@ jobs: assert core_path == installed.locate_file("apcore/__init__.py").resolve() assert toolkit_path == toolkit_expected.resolve() if os.environ["CORE_MODE"] == "candidate": - assert installed.version == "1.0.0a3" + assert installed.version == "1.0.0a4" origin = json.loads(installed.read_text("direct_url.json") or "{}") assert origin.get("url") == Path(os.environ["CORE_INSTALL"]).resolve().as_uri() assert callable(getattr(Executor, "stream_with_completion", None)) @@ -340,7 +340,7 @@ jobs: assert.ok(coreEntry.startsWith(core + sep)); assert.equal(toolkitEntry, realpathSync(resolve(process.env.TOOLKIT_ROOT, 'dist/index.js'))); if (process.env.CORE_MODE === 'candidate') { - assert.equal(coreVersion, '1.0.0-alpha.3'); + assert.equal(coreVersion, '1.0.0-alpha.4'); assert.equal(typeof Executor.prototype.streamWithCompletion, 'function'); assert.equal(typeof APCore.prototype.streamWithCompletion, 'function'); } else { @@ -406,7 +406,7 @@ jobs: crate="${crates[0]}" version="${crate##*/apcore-}" version="${version%.crate}" - if [[ "$version" != 1.0.0-alpha.3 ]]; then + if [[ "$version" != 1.0.0-alpha.4 ]]; then echo "Expected the alpha.3 Core crate." >&2 exit 1 fi diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 9a831468..23ddd725 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -15,7 +15,7 @@ permissions: contents: read env: - CORE_REF: 9ba719587d9a288c22b8b5ff2a10a187a9a21cee + CORE_REF: de0c797760796daeefc1ba70d1e44263ea6519f1 jobs: test: diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 876dad44..8abb6089 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -22,9 +22,9 @@ permissions: env: # The released lockfiles already reference these prereleases. Bootstrap CI # from the reviewed Core commit while those versions are unpublished. - CORE_REF: 9ba719587d9a288c22b8b5ff2a10a187a9a21cee - CORE_CRATE_VERSION: 1.0.0-alpha.3 - CORE_CRATE_SHA256: 2813101192ceac629d58114dfafd4f6b519eb7dea2313cb253e1410a2ac52f65 + CORE_REF: de0c797760796daeefc1ba70d1e44263ea6519f1 + CORE_CRATE_VERSION: 1.0.0-alpha.4 + CORE_CRATE_SHA256: 412082f3f58f5a59165f20e1df00f7191b5e382ea59f2369eb486f963cb7d604 jobs: source: diff --git a/.github/workflows/typescript.yml b/.github/workflows/typescript.yml index e35a0a3d..e526cb48 100644 --- a/.github/workflows/typescript.yml +++ b/.github/workflows/typescript.yml @@ -15,7 +15,7 @@ permissions: contents: read env: - CORE_REF: 9ba719587d9a288c22b8b5ff2a10a187a9a21cee + CORE_REF: de0c797760796daeefc1ba70d1e44263ea6519f1 jobs: test: diff --git a/a2a/python/pyproject.toml b/a2a/python/pyproject.toml index 3de6d192..3d3b5ab8 100644 --- a/a2a/python/pyproject.toml +++ b/a2a/python/pyproject.toml @@ -26,7 +26,7 @@ classifiers = [ "Framework :: AsyncIO", ] dependencies = [ - "apcore[config,discovery]==1.0.0a3", + "apcore[config,discovery]==1.0.0a4", "apcore-toolkit==0.15.1a2", "a2a-sdk[http-server]>=1.1.2", "starlette>=0.40.0", diff --git a/a2a/rust/Cargo.lock b/a2a/rust/Cargo.lock index dd20ae49..723973af 100644 --- a/a2a/rust/Cargo.lock +++ b/a2a/rust/Cargo.lock @@ -92,9 +92,9 @@ dependencies = [ [[package]] name = "apcore" -version = "1.0.0-alpha.3" +version = "1.0.0-alpha.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2813101192ceac629d58114dfafd4f6b519eb7dea2313cb253e1410a2ac52f65" +checksum = "412082f3f58f5a59165f20e1df00f7191b5e382ea59f2369eb486f963cb7d604" dependencies = [ "async-stream", "async-trait", diff --git a/a2a/rust/Cargo.toml b/a2a/rust/Cargo.toml index 142fd7e5..4c69cd00 100644 --- a/a2a/rust/Cargo.toml +++ b/a2a/rust/Cargo.toml @@ -27,7 +27,7 @@ default = [] openapi = ["apcore-toolkit/http-proxy"] [dependencies] -apcore = { version = "=1.0.0-alpha.3", default-features = false, features = ["discovery", "sys-modules"] } +apcore = { version = "=1.0.0-alpha.4", default-features = false, features = ["discovery", "sys-modules"] } # `default-features = false` so `http-proxy` — a *default* feature of the # toolkit — is reached through this crate's `openapi` feature instead of being # enabled unconditionally. The unconditional import (`deep_resolve_refs`) is diff --git a/a2a/typescript/package.json b/a2a/typescript/package.json index d5348e47..7299482b 100644 --- a/a2a/typescript/package.json +++ b/a2a/typescript/package.json @@ -33,7 +33,7 @@ }, "dependencies": { "@a2a-js/sdk": ">=1.0.1", - "apcore-js": "1.0.0-alpha.3", + "apcore-js": "1.0.0-alpha.4", "apcore-toolkit": "0.15.1-alpha.2", "express": "^5.1.0", "jsonwebtoken": "^9.0.3", diff --git a/a2a/typescript/pnpm-lock.yaml b/a2a/typescript/pnpm-lock.yaml index c828fa48..2c83beac 100644 --- a/a2a/typescript/pnpm-lock.yaml +++ b/a2a/typescript/pnpm-lock.yaml @@ -12,8 +12,8 @@ importers: specifier: '>=1.0.1' version: 1.0.1(express@5.2.1) apcore-js: - specifier: 1.0.0-alpha.3 - version: 1.0.0-alpha.3(typescript@5.9.3) + specifier: 1.0.0-alpha.4 + version: 1.0.0-alpha.4(typescript@5.9.3) apcore-toolkit: specifier: 0.15.1-alpha.2 version: 0.15.1-alpha.2(@sinclair/typebox@0.34.48)(typescript@5.9.3) @@ -656,8 +656,8 @@ packages: ajv@8.20.0: resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==} - apcore-js@1.0.0-alpha.3: - resolution: {integrity: sha512-0zv5xlVunNaa7GhbeJsgG0q6Dd97+f3T/kFrRyhzIkVc957aX87bhWLMlhgqhg/4iFZ1ZWDXl15kxOE1xbCPqw==} + apcore-js@1.0.0-alpha.4: + resolution: {integrity: sha512-Ix49EPRQBVezM4mp59wGNW3AI7RFvD1I9iwPoYp/F81/gUZQIJ1CLjQkcFsiNME14EIGmcLL+noa/ttVg6qIcQ==} engines: {node: '>=20.0.0'} peerDependencies: typescript: ^5.5.0 @@ -1951,7 +1951,7 @@ snapshots: json-schema-traverse: 1.0.0 require-from-string: 2.0.2 - apcore-js@1.0.0-alpha.3(typescript@5.9.3): + apcore-js@1.0.0-alpha.4(typescript@5.9.3): dependencies: '@sinclair/typebox': 0.34.48 js-yaml: 4.3.2 @@ -1963,7 +1963,7 @@ snapshots: dependencies: '@sinclair/typebox': 0.34.48 ajv: 8.20.0 - apcore-js: 1.0.0-alpha.3(typescript@5.9.3) + apcore-js: 1.0.0-alpha.4(typescript@5.9.3) js-yaml: 4.3.2 transitivePeerDependencies: - typescript diff --git a/cli/python/pyproject.toml b/cli/python/pyproject.toml index 49583d8b..97f57b0b 100644 --- a/cli/python/pyproject.toml +++ b/cli/python/pyproject.toml @@ -26,7 +26,7 @@ classifiers = [ "Environment :: Console", ] dependencies = [ - "apcore[config,discovery]==1.0.0a3", + "apcore[config,discovery]==1.0.0a4", "apcore-toolkit[http-proxy]==0.15.1a2", "click>=8.1", "jsonschema>=4.20", diff --git a/cli/rust/Cargo.lock b/cli/rust/Cargo.lock index c03e5127..405eaf98 100644 --- a/cli/rust/Cargo.lock +++ b/cli/rust/Cargo.lock @@ -133,9 +133,9 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "apcore" -version = "1.0.0-alpha.3" +version = "1.0.0-alpha.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2813101192ceac629d58114dfafd4f6b519eb7dea2313cb253e1410a2ac52f65" +checksum = "412082f3f58f5a59165f20e1df00f7191b5e382ea59f2369eb486f963cb7d604" dependencies = [ "async-stream", "async-trait", diff --git a/cli/rust/Cargo.toml b/cli/rust/Cargo.toml index 2e08e1da..2d4fb496 100644 --- a/cli/rust/Cargo.toml +++ b/cli/rust/Cargo.toml @@ -21,7 +21,7 @@ name = "apcore_cli" path = "src/lib.rs" [dependencies] -apcore = { version = "=1.0.0-alpha.3", default-features = false, features = ["config"] } +apcore = { version = "=1.0.0-alpha.4", default-features = false, features = ["config"] } async-trait = "0.1" clap = { version = "4", features = ["derive", "env", "string"] } serde = { version = "1", features = ["derive"] } diff --git a/cli/typescript/package.json b/cli/typescript/package.json index 638ece90..cee57a3d 100644 --- a/cli/typescript/package.json +++ b/cli/typescript/package.json @@ -30,7 +30,7 @@ "node": ">=20.0.0" }, "peerDependencies": { - "apcore-js": "1.0.0-alpha.3", + "apcore-js": "1.0.0-alpha.4", "apcore-toolkit": "0.15.1-alpha.2" }, "dependencies": { @@ -47,7 +47,7 @@ "@typescript-eslint/eslint-plugin": "^8.59.0", "@typescript-eslint/parser": "^8.59.0", "@vitest/coverage-v8": "^5.1.0", - "apcore-js": "1.0.0-alpha.3", + "apcore-js": "1.0.0-alpha.4", "apcore-toolkit": "0.15.1-alpha.2", "apdev-js": "^0.2.4", "eslint": "^10.2.1", diff --git a/cli/typescript/pnpm-lock.yaml b/cli/typescript/pnpm-lock.yaml index 05895b2d..55b96549 100644 --- a/cli/typescript/pnpm-lock.yaml +++ b/cli/typescript/pnpm-lock.yaml @@ -34,8 +34,8 @@ importers: specifier: ^5.1.0 version: 5.1.0(vitest@5.1.0) apcore-js: - specifier: 1.0.0-alpha.3 - version: 1.0.0-alpha.3(typescript@5.9.3) + specifier: 1.0.0-alpha.4 + version: 1.0.0-alpha.4(typescript@5.9.3) apcore-toolkit: specifier: 0.15.1-alpha.2 version: 0.15.1-alpha.2(@sinclair/typebox@0.34.48)(typescript@5.9.3) @@ -731,8 +731,8 @@ packages: any-promise@1.3.0: resolution: {integrity: sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==} - apcore-js@1.0.0-alpha.3: - resolution: {integrity: sha512-0zv5xlVunNaa7GhbeJsgG0q6Dd97+f3T/kFrRyhzIkVc957aX87bhWLMlhgqhg/4iFZ1ZWDXl15kxOE1xbCPqw==} + apcore-js@1.0.0-alpha.4: + resolution: {integrity: sha512-Ix49EPRQBVezM4mp59wGNW3AI7RFvD1I9iwPoYp/F81/gUZQIJ1CLjQkcFsiNME14EIGmcLL+noa/ttVg6qIcQ==} engines: {node: '>=20.0.0'} peerDependencies: typescript: ^5.5.0 @@ -1944,7 +1944,7 @@ snapshots: any-promise@1.3.0: {} - apcore-js@1.0.0-alpha.3(typescript@5.9.3): + apcore-js@1.0.0-alpha.4(typescript@5.9.3): dependencies: '@sinclair/typebox': 0.34.48 js-yaml: 4.3.2 @@ -1956,7 +1956,7 @@ snapshots: dependencies: '@sinclair/typebox': 0.34.48 ajv: 8.20.0 - apcore-js: 1.0.0-alpha.3(typescript@5.9.3) + apcore-js: 1.0.0-alpha.4(typescript@5.9.3) js-yaml: 4.3.2 transitivePeerDependencies: - typescript diff --git a/mcp/conformance/fixtures/system_surface.json b/mcp/conformance/fixtures/system_surface.json index 773e8e9d..19c551ab 100644 --- a/mcp/conformance/fixtures/system_surface.json +++ b/mcp/conformance/fixtures/system_surface.json @@ -1,8 +1,8 @@ { - "description": "The nine canonical system.* modules -> exact MCP primitive, name/URI. Pins aiperceivable/apcore-mcp#15's classification table (system.health.*/system.usage.*/system.manifest.* are resources or resource templates; system.control.* stays a tool) and operationalizes the issue's 'byte-identical tools/list, resources/list, resources/templates/list across TypeScript, Python and Rust' acceptance criterion: given a registry produced by the SAME real registerSysModules()/register_sys_modules() call (sys_modules.enabled=true, sys_modules.events.enabled=true), each adapter's own tool/resource projection MUST produce exactly the entries below -- not merely an equivalent shape. A single-language fix (e.g. only one adapter emitting the RFC 6570 '{?period}' query-expansion on a template) is exactly the drift this fixture exists to catch.", + "description": "The ten canonical system.* modules -> exact MCP primitive, name/URI. Pins aiperceivable/apcore-mcp#15's classification table (administrative system.health, system.usage, and system.manifest reads are resources; control modules and system.manifest.search are tools) and operationalizes the issue's 'byte-identical tools/list, resources/list, resources/templates/list across TypeScript, Python and Rust' acceptance criterion: given a registry produced by the SAME real registerSysModules()/register_sys_modules() call (sys_modules.enabled=true, sys_modules.events.enabled=true), each adapter's own tool/resource projection MUST produce exactly the entries below -- not merely an equivalent shape. A single-language fix (e.g. only one adapter emitting the RFC 6570 '{?period}' query-expansion on a template) is exactly the drift this fixture exists to catch.", "spec": "PROTOCOL_SPEC.md#6.6.2 (classification by module_id prefix only), aiperceivable/apcore-mcp#15 (URI convention table), aiperceivable/apcore-mcp#16 Phase A (surfaces grouping)", "setup": { - "description": "Build the registry that produces all nine module ids: sys_modules.enabled=true AND sys_modules.events.enabled=true. Without the events flag only the six read-only modules register and 'system.control.*' matches nothing -- see aiperceivable/apcore-mcp#15's registration-ladder table (0 / 6 / 9 modules).", + "description": "Build the registry that produces all ten module ids: sys_modules.enabled=true AND sys_modules.events.enabled=true. Without the events flag only the seven read-only modules register and 'system.control.*' matches nothing -- see aiperceivable/apcore-mcp#15's registration-ladder table (0 / 7 / 10 modules).", "config": { "sys_modules": { "enabled": true, @@ -13,7 +13,8 @@ "tools": [ { "module_id": "system.control.update_config", "name": "system.control.update_config" }, { "module_id": "system.control.reload_module", "name": "system.control.reload_module" }, - { "module_id": "system.control.toggle_feature", "name": "system.control.toggle_feature" } + { "module_id": "system.control.toggle_feature", "name": "system.control.toggle_feature" }, + { "module_id": "system.manifest.search", "name": "system.manifest.search" } ], "not_tools": [ "system.health.summary", @@ -33,7 +34,7 @@ { "module_id": "system.usage.module", "uri_template": "apcore://system.usage.module/{module_id}{?period}", - "note": "The only one of the nine modules whose declared template carries the RFC 6570 form-style query expansion '{?period}' -- system.usage.summary's optional ?period= is accepted at read time but is NOT part of its (non-template) resource's declared uri, since a concrete Resource.uri cannot carry template syntax." + "note": "The only one module whose declared template carries the RFC 6570 form-style query expansion '{?period}' -- system.usage.summary's optional ?period= is accepted at read time but is NOT part of its (non-template) resource's declared uri, since a concrete Resource.uri cannot carry template syntax." }, { "module_id": "system.manifest.module", "uri_template": "apcore://system.manifest.module/{module_id}" } ], diff --git a/mcp/docs/index.md b/mcp/docs/index.md index d3bd8595..2383dbf4 100644 --- a/mcp/docs/index.md +++ b/mcp/docs/index.md @@ -41,6 +41,7 @@ If you have already built modules using the `apcore` framework (which focuses on - **Three transports** — stdio (default, for desktop clients), Streamable HTTP, and SSE. - **Annotation mapping** — apcore annotations (readonly, destructive, idempotent) map to MCP ToolHints. - **Schema conversion** — JSON Schema `$ref`/`$defs` inlining, strict mode for OpenAI Structured Outputs. +- **Caller-aware discovery** — Core-backed servers filter the standard tool list and module documentation resources using the current caller's ACL visibility. The tool list retains complete input schemas. When enabled, `system.manifest.search` provides lightweight, paginated summaries under its own ACL. - **Tool Explorer** — Built-in browser UI for exploring and testing MCP tools (like Swagger UI for MCP). - **JWT Authentication** — Optional Bearer token auth for HTTP-based transports. - **Approval Mechanism** — Bridges MCP elicitation to apcore's runtime approval system. diff --git a/mcp/python/pyproject.toml b/mcp/python/pyproject.toml index 35e31681..ed1a111b 100644 --- a/mcp/python/pyproject.toml +++ b/mcp/python/pyproject.toml @@ -25,7 +25,7 @@ classifiers = [ "Topic :: Scientific/Engineering :: Artificial Intelligence", ] dependencies = [ - "apcore[config,discovery]==1.0.0a3", + "apcore[config,discovery]==1.0.0a4", "mcp>=1.26,<2.0", "jsonschema>=4.20,<5", "referencing>=0.30,<1", diff --git a/mcp/python/src/apcore_mcp/apcore_mcp.py b/mcp/python/src/apcore_mcp/apcore_mcp.py index 4cd2eb12..582782fe 100644 --- a/mcp/python/src/apcore_mcp/apcore_mcp.py +++ b/mcp/python/src/apcore_mcp/apcore_mcp.py @@ -717,7 +717,10 @@ def _build_server_components(self) -> tuple[Any, Any, list, Any, str]: factory = MCPServerFactory() server = factory.create_server(name=self._name, version=version) - tools = factory.build_tools(self._registry, tags=self._tags, prefix=self._prefix) + discovery_sources: dict[int, str] = {} + tools = factory.build_tools( + self._registry, tags=self._tags, prefix=self._prefix, discovery_sources=discovery_sources, + ) router = ExecutionRouter( self._executor, @@ -757,6 +760,7 @@ def _build_server_components(self) -> tuple[Any, Any, list, Any, str]: async_bridge=async_bridge, approval_bridge=approval_bridge, descriptor_lookup=descriptor_lookup, + discovery_sources=discovery_sources, ) factory.register_resource_handlers(server, self._registry, router) diff --git a/mcp/python/src/apcore_mcp/server/factory.py b/mcp/python/src/apcore_mcp/server/factory.py index 81f720e7..f3668539 100644 --- a/mcp/python/src/apcore_mcp/server/factory.py +++ b/mcp/python/src/apcore_mcp/server/factory.py @@ -439,6 +439,7 @@ def build_tools( prefix: str | None = None, *, strict: bool | None = None, + discovery_sources: dict[int, str] | None = None, ) -> list[mcp_types.Tool]: """Build Tool objects for all modules in a Registry. @@ -481,7 +482,10 @@ def build_tools( ): descriptor = selected # Keep compatibility arguments while preserving the runtime schema. - tools.append(self.build_tool(descriptor, registry=registry, strict=strict)) + tool = self.build_tool(descriptor, registry=registry, strict=strict) + if discovery_sources is not None: + discovery_sources[id(tool)] = module_id + tools.append(tool) except ValueError as e: # Reserved-prefix violations are hard config errors — re-raise so # misconfiguration is visible at startup rather than silently @@ -543,6 +547,7 @@ def register_handlers( async_bridge: AsyncTaskBridge | None = None, approval_bridge: ApprovalBridge | None = None, descriptor_lookup: Any = None, + discovery_sources: dict[int, str] | None = None, ) -> None: """Register list_tools and call_tool handlers on the Server. @@ -577,14 +582,34 @@ def register_handlers( _protect_sdk_approval_logs(server) regular_tool_ids = {id(tool) for tool in tools} + captured_sources = discovery_sources or {} + caller_aware = isinstance(router, ExecutionRouter) and router.supports_capability_discovery + + def visible_tool(tool: mcp_types.Tool, identity: Identity | None) -> mcp_types.Tool | None: + if not caller_aware or id(tool) not in regular_tool_ids: + return tool + module_id = captured_sources.get(id(tool), tool.name) + descriptor = router.callable_descriptor(module_id, identity, tool_default=True) + if descriptor is None: + return None + try: + live_tool = self.build_tool(descriptor) + except ValueError: + return None + return live_tool if live_tool.name == tool.name else None @server.list_tools() async def handle_list_tools() -> list[mcp_types.Tool]: + identity = _request_identity() + listed = [live for tool in combined_tools if (live := visible_tool(tool, identity)) is not None] if _supports_structured_output(): - return list(combined_tools) - return [tool.model_copy(update={"outputSchema": None}) for tool in combined_tools] + return listed + return [tool.model_copy(update={"outputSchema": None}) for tool in listed] - @server.call_tool() + # The MCP SDK's schema cache is shared across request identities. Core + # validates on dispatch, and any prevalidation here uses a live tool + # descriptor scoped to this caller. + @server.call_tool(validate_input=not caller_aware) async def handle_call_tool(name: str, arguments: dict[str, Any]) -> mcp_types.CallToolResult: from mcp.server.lowlevel.server import request_ctx @@ -622,6 +647,15 @@ async def send_notification(notification: dict[str, Any]) -> None: published = next((tool for tool in reversed(combined_tools) if tool.name == name), None) regular_tool = published is not None and id(published) in regular_tool_ids + if published is not None and caller_aware: + live_tool = visible_tool(published, identity) + if live_tool is not None: + try: + jsonschema.validate(instance=arguments or {}, schema=live_tool.inputSchema) + except jsonschema.ValidationError as error: + message = mcp_types.TextContent(type="text", text=f"Input validation error: {error.message}") + return _build_call_result([message], True, None) + published = live_tool if published is not None and regular_tool and isinstance(router, ExecutionRouter): error = self._bind_requested_version( router, @@ -827,10 +861,23 @@ def register_resource_handlers( static_system_ids = [mid for mid in _SYSTEM_STATIC_RESOURCE_IDS if mid in registered_ids] if router else [] template_system_ids = [mid for mid in _SYSTEM_TEMPLATE_RESOURCE_IDS if mid in registered_ids] if router else [] + caller_aware = isinstance(router, ExecutionRouter) and router.supports_capability_discovery + + def visible_documentation(module_id: str, identity: Identity | None) -> str | None: + if module_id not in docs_map: + return None + if not caller_aware: + return docs_map[module_id] + descriptor = router.callable_descriptor(module_id, identity) + return descriptor.documentation if descriptor is not None else None + @server.list_resources() async def handle_list_resources() -> list[mcp_types.Resource]: + identity = _request_identity() resources: list[mcp_types.Resource] = [] for mid in docs_map: + if not visible_documentation(mid, identity): + continue resources.append( mcp_types.Resource( uri=AnyUrl(f"docs://{mid}"), @@ -876,9 +923,10 @@ async def handle_read_resource(uri: Any) -> list[ReadResourceContents]: if not uri_str.startswith(docs_prefix): raise ValueError(f"Unsupported URI scheme: {uri_str}") module_id = uri_str[len(docs_prefix) :] - if module_id not in docs_map: + documentation = visible_documentation(module_id, _request_identity()) + if not documentation: raise ValueError(f"Resource not found: {uri_str}") - return [ReadResourceContents(content=docs_map[module_id], mime_type="text/plain")] + return [ReadResourceContents(content=documentation, mime_type="text/plain")] async def _read_system_resource( self, diff --git a/mcp/python/src/apcore_mcp/server/router.py b/mcp/python/src/apcore_mcp/server/router.py index 5a8ba034..5cc3d6c5 100644 --- a/mcp/python/src/apcore_mcp/server/router.py +++ b/mcp/python/src/apcore_mcp/server/router.py @@ -12,7 +12,7 @@ from contextlib import aclosing from typing import Any -from apcore import APCore, CancelToken, Context, Executor, ModuleError, StreamingModule +from apcore import APCore, CancelToken, Context, Executor, Identity, ModuleError, StreamingModule from apcore.errors import ApprovalPendingError from apcore.registry.types import ModuleDescriptor from apcore.registry.version import matches_version_hint @@ -224,6 +224,23 @@ def _maybe_redact(self, tool_name: str, result: Any, output_schema: dict[str, An logger.warning("redact_sensitive failed for %s, returning unredacted output", tool_name, exc_info=True) return result + @property + def supports_capability_discovery(self) -> bool: + return self._core_backend and callable(getattr(self._executor, "get_callable_descriptor", None)) + + def callable_descriptor( + self, module_id: str, identity: Identity | None, *, tool_default: bool = False + ) -> ModuleDescriptor | None: + """Project from the same caller frame and Executor as tool invocation.""" + context = Context.create(identity=identity) + descriptor = self._executor.get_callable_descriptor(module_id, context) + if descriptor is None or not tool_default: + return descriptor + version_hint = _descriptor_version_hint(descriptor) + if version_hint is None: + return descriptor + return self._executor.get_callable_descriptor(module_id, context, version_hint=version_hint) + def _select_wire_version( self, tool_name: str, extra: dict[str, Any] ) -> tuple[ModuleDescriptor, ModuleDescriptor | None, bool] | None: diff --git a/mcp/python/tests/server/test_capability_discovery.py b/mcp/python/tests/server/test_capability_discovery.py new file mode 100644 index 00000000..3ccf9336 --- /dev/null +++ b/mcp/python/tests/server/test_capability_discovery.py @@ -0,0 +1,121 @@ +"""Caller-aware discovery through the actual MCP HTTP and in-memory transports.""" + +from __future__ import annotations + +import json + +import httpx +from apcore import ACL, ACLRule, Executor, Identity, Registry + +from apcore_mcp import APCoreMCP +from tests.server.test_scoped_approval_wire import _HttpSession +from tests.server.test_versioned_tool_wire import connected_client + + +class Report: + description = "Return a synthetic report" + documentation = "Report documentation." + input_schema = { + "type": "object", + "$defs": {"Count": {"type": "integer"}}, + "properties": {"count": {"$ref": "#/$defs/Count"}}, + "required": ["count"], + } + output_schema = {"type": "object"} + + def __init__(self) -> None: + self.calls = 0 + + async def execute(self, inputs, _context): + self.calls += 1 + return inputs + + +async def test_discovery_is_bound_to_http_identity_and_does_not_weaken_execution() -> None: + module_id = "fixture.report" + registry = Registry() + report = Report() + registry.register(module_id, report, metadata={"documentation": Report.documentation}) + audits = [] + acl = ACL( + [ACLRule(callers=["@external"], targets=[module_id], effect="allow", conditions={"roles": ["reporter"]})], + audit_logger=audits.append, + ) + + class Authenticator: + def authenticate(self, headers): + return { + "Bearer reporter": Identity(id="reporter", roles=("reporter",)), + "Bearer guest": Identity(id="guest", roles=("guest",)), + }.get(headers.get("authorization")) + + mcp = APCoreMCP(Executor(registry, acl=acl), authenticator=Authenticator(), async_tasks=False) + async with mcp.async_serve() as app, httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://localhost", + ) as client: + reporter = _HttpSession(client, "Bearer reporter") + guest = _HttpSession(client, "Bearer guest") + await reporter.initialize() + await guest.initialize() + tools = (await reporter.request("tools/list", {}))["tools"] + assert [tool["name"] for tool in tools] == [module_id] + assert tools[0]["inputSchema"] == Report.input_schema + assert (await guest.request("tools/list", {}))["tools"] == [] + uri = f"docs://{module_id}" + assert [resource["uri"] for resource in (await reporter.request("resources/list", {}))["resources"]] == [uri] + assert (await guest.request("resources/list", {}))["resources"] == [] + docs = await reporter.request("resources/read", {"uri": uri}) + assert docs["contents"][0]["text"] == Report.documentation + denied = await client.post("/mcp/", headers=guest.headers, json={ + "jsonrpc": "2.0", "method": "resources/read", "params": {"uri": uri}, "id": 999, + }) + body = denied.json() if denied.headers["content-type"].startswith("application/json") else json.loads( + next(line[6:] for line in denied.text.splitlines() if line.startswith("data: ")) + ) + assert "error" in body + assert Report.documentation not in denied.text + assert audits == [] and report.calls == 0 + + call = {"name": module_id, "arguments": {"count": 3}} + await reporter.request("tools/list", {}) + denied_call = await guest.request("tools/call", {**call, "arguments": {"count": "invalid"}}) + assert denied_call["isError"] + assert "Input validation error" not in denied_call["content"][0]["text"] + assert not (await reporter.request("tools/call", call))["isError"] + assert len(audits) == 2 and report.calls == 1 + + +async def test_anonymous_mcp_listing_proves_public_access() -> None: + registry = Registry() + registry.register("fixture.report", Report(), metadata={"documentation": Report.documentation}) + acl = ACL([ACLRule(callers=["@external"], targets=["fixture.report"], effect="allow", conditions={ + "roles": ["reporter"], + })]) + async with connected_client(Executor(registry, acl=acl), async_tasks=False) as session: + assert (await session.list_tools()).tools == [] + assert (await session.list_resources()).resources == [] + + + +async def test_discovery_reads_the_current_same_version_registration() -> None: + registry = Registry() + module_id = "fixture.report" + registry.register(module_id, Report(), version="1.0.0", metadata={"documentation": "Original content."}) + async with connected_client(registry, async_tasks=False) as session: + existing = (await session.list_tools()).tools[0] + assert existing.inputSchema["required"] == ["count"] + + registry.unregister(module_id) + replacement = Report() + replacement_schema = { + "type": "object", + "properties": {"label": {"type": "string"}}, + "required": ["label"], + } + replacement.input_schema = replacement_schema + registry.register(module_id, replacement, version="1.0.0", metadata={"documentation": "Updated content."}) + + current = (await session.list_tools()).tools[0] + assert current.inputSchema == replacement_schema + resource = await session.read_resource(f"docs://{module_id}") + assert resource.contents[0].text == "Updated content." diff --git a/mcp/python/tests/test_api.py b/mcp/python/tests/test_api.py index c4eef386..4dfb8008 100644 --- a/mcp/python/tests/test_api.py +++ b/mcp/python/tests/test_api.py @@ -231,7 +231,7 @@ def test_serve_stdio_wires_components(self, registry): serve(registry, transport="stdio", name="test-server", version="1.0.0") mock_factory.create_server.assert_called_once_with(name="test-server", version="1.0.0") - mock_factory.build_tools.assert_called_once_with(registry, tags=None, prefix=None) + mock_factory.build_tools.assert_called_once_with(registry, tags=None, prefix=None, discovery_sources={}) mock_factory.register_handlers.assert_called_once() mock_factory.build_init_options.assert_called_once() @@ -345,4 +345,6 @@ def test_serve_with_executor(self, executor): trace=False, ) # Factory should receive the extracted registry - mock_factory.build_tools.assert_called_once_with(executor.registry, tags=None, prefix=None) + mock_factory.build_tools.assert_called_once_with( + executor.registry, tags=None, prefix=None, discovery_sources={}, + ) diff --git a/mcp/python/tests/test_management_surfaces.py b/mcp/python/tests/test_management_surfaces.py index 10de6b1b..250a2908 100644 --- a/mcp/python/tests/test_management_surfaces.py +++ b/mcp/python/tests/test_management_surfaces.py @@ -204,9 +204,11 @@ def test_unprotected_system_control_warns_on_build(self, caplog: pytest.LogCaptu ext = dumped["extensions"]["com.aiperceivable/management"] assert set(ext["surfaces"]) == {"health", "usage", "manifest", "control"} - # Read-only system.* modules must not appear as tools. + # The caller-scoped search is a tool; the administrative reads are resources. tool_names = {t.name for t in tools} - assert not any(name.startswith(("system.health.", "system.usage.", "system.manifest.")) for name in tool_names) + assert "system.manifest.search" in tool_names + admin_tools = tool_names - {"system.manifest.search"} + assert not any(name.startswith(("system.health.", "system.usage.", "system.manifest.")) for name in admin_tools) assert "system.control.reload_module" in tool_names def test_acl_protected_control_surface_does_not_warn(self, caplog: pytest.LogCaptureFixture) -> None: diff --git a/mcp/python/tests/test_serve_params.py b/mcp/python/tests/test_serve_params.py index 531e75e6..1c6423ef 100644 --- a/mcp/python/tests/test_serve_params.py +++ b/mcp/python/tests/test_serve_params.py @@ -122,28 +122,30 @@ def test_build_tools_called_with_tags_and_prefix(self, registry): with self._patch_server() as mock_factory: serve(registry, tags=["image"], prefix="image.") - mock_factory.build_tools.assert_called_once_with(registry, tags=["image"], prefix="image.") + mock_factory.build_tools.assert_called_once_with( + registry, tags=["image"], prefix="image.", discovery_sources={}, + ) def test_build_tools_called_with_tags_only(self, registry): """When only tags is provided, prefix defaults to None.""" with self._patch_server() as mock_factory: serve(registry, tags=["text"]) - mock_factory.build_tools.assert_called_once_with(registry, tags=["text"], prefix=None) + mock_factory.build_tools.assert_called_once_with(registry, tags=["text"], prefix=None, discovery_sources={}) def test_build_tools_called_with_prefix_only(self, registry): """When only prefix is provided, tags defaults to None.""" with self._patch_server() as mock_factory: serve(registry, prefix="text") - mock_factory.build_tools.assert_called_once_with(registry, tags=None, prefix="text") + mock_factory.build_tools.assert_called_once_with(registry, tags=None, prefix="text", discovery_sources={}) def test_build_tools_called_without_tags_or_prefix(self, registry): """When neither tags nor prefix is provided, both default to None.""" with self._patch_server() as mock_factory: serve(registry) - mock_factory.build_tools.assert_called_once_with(registry, tags=None, prefix=None) + mock_factory.build_tools.assert_called_once_with(registry, tags=None, prefix=None, discovery_sources={}) # =========================================================================== diff --git a/mcp/python/tests/test_system_surface_conformance.py b/mcp/python/tests/test_system_surface_conformance.py index d64ab9df..c8e710cd 100644 --- a/mcp/python/tests/test_system_surface_conformance.py +++ b/mcp/python/tests/test_system_surface_conformance.py @@ -1,4 +1,4 @@ -"""Cross-language conformance: the nine canonical system.* modules -> exact MCP primitive. +"""Cross-language conformance: the canonical system.* modules -> exact MCP primitive. Drives ``MCPServerFactory.build_tools`` / ``register_resource_handlers`` from the shared fixture at ``apcore-mcp/conformance/fixtures/system_surface.json``, @@ -45,7 +45,7 @@ def real_registry() -> Registry: return registry -def test_control_modules_are_tools(real_registry: Registry) -> None: +def test_control_and_search_modules_are_tools(real_registry: Registry) -> None: """The `system.*` tool set must equal the fixture's exactly — not merely contain it. A subset assertion would let an adapter emit an *extra* management tool and @@ -63,7 +63,7 @@ def test_control_modules_are_tools(real_registry: Registry) -> None: ) -def test_readonly_system_modules_are_not_tools(real_registry: Registry) -> None: +def test_administrative_read_modules_are_resources(real_registry: Registry) -> None: tools = MCPServerFactory().build_tools(real_registry) tool_names = {t.name for t in tools} diff --git a/mcp/rust/Cargo.lock b/mcp/rust/Cargo.lock index 51f58c00..d013613b 100644 --- a/mcp/rust/Cargo.lock +++ b/mcp/rust/Cargo.lock @@ -98,9 +98,9 @@ dependencies = [ [[package]] name = "apcore" -version = "1.0.0-alpha.3" +version = "1.0.0-alpha.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2813101192ceac629d58114dfafd4f6b519eb7dea2313cb253e1410a2ac52f65" +checksum = "412082f3f58f5a59165f20e1df00f7191b5e382ea59f2369eb486f963cb7d604" dependencies = [ "async-stream", "async-trait", diff --git a/mcp/rust/Cargo.toml b/mcp/rust/Cargo.toml index 7586807a..2df10dd2 100644 --- a/mcp/rust/Cargo.toml +++ b/mcp/rust/Cargo.toml @@ -22,7 +22,7 @@ all-features = true rustdoc-args = ["--cfg", "docsrs"] [dependencies] -apcore = { version = "=1.0.0-alpha.3", default-features = false, features = ["config", "sys-modules"] } +apcore = { version = "=1.0.0-alpha.4", default-features = false, features = ["config", "sys-modules"] } apcore-toolkit = "=0.15.1-alpha.2" mcp-embedded-ui = "0.5" tokio = { version = "1", features = ["full"] } diff --git a/mcp/rust/src/apcore_mcp.rs b/mcp/rust/src/apcore_mcp.rs index c198ce46..5f816313 100644 --- a/mcp/rust/src/apcore_mcp.rs +++ b/mcp/rust/src/apcore_mcp.rs @@ -250,6 +250,20 @@ struct ApcoreExecutorAdapter { #[async_trait::async_trait] impl crate::server::router::Executor for ApcoreExecutorAdapter { + fn discovery_executor( + &self, + want_trace: bool, + ) -> Option<(&Executor, &apcore::ExecutionStrategy)> { + let strategy = if want_trace { + self.strategy + .as_deref() + .unwrap_or_else(|| self.inner.strategy()) + } else { + self.inner.strategy() + }; + Some((&self.inner, strategy)) + } + async fn call_async( &self, module_id: &str, @@ -551,6 +565,11 @@ impl APCoreMCP { .clone() .unwrap_or_else(|| crate::VERSION.to_string()); + // Enable manifest search on raw Core executors as well as APCore. + if self.reg().has("system.manifest.search") { + self.executor.enable_nested_calls(); + } + let factory = MCPServerFactory::new(); let mut server = factory .create_server(&self.config.name, &version) @@ -636,6 +655,14 @@ impl APCoreMCP { // Register handlers factory.register_handlers(&mut server, tools.clone(), Arc::clone(&router)); + factory.register_governed_tools( + &mut server, + Arc::clone(&router), + &tools, + self.config.tags.clone(), + self.config.prefix.clone(), + ); + // Register resource handlers. Reads dispatch through `router` so the // system.* resources added by #15(a) get the same ACL / approval / // redaction path a tools/call gets. @@ -2653,6 +2680,195 @@ mod tests { serde_json::from_slice(&bytes).unwrap() } + struct DiscoveryFixtureAuth; + + #[async_trait::async_trait] + impl crate::auth::protocol::Authenticator for DiscoveryFixtureAuth { + async fn authenticate( + &self, + headers: &std::collections::HashMap, + ) -> Option { + let role = headers.get("x-test-role")?.clone(); + Some(apcore::Identity::new( + role.clone(), + "user".into(), + vec![role], + std::collections::HashMap::new(), + )) + } + } + + fn register_discovery_fixture(registry: &Registry, property: &str) { + let id = "demo.governed"; + let module = MockModule::new("Governed tool"); + let descriptor = ModuleDescriptor { + module_id: id.into(), + name: None, + description: format!("Current tool uses {property}"), + documentation: Some(format!("Current documentation: {property}")), + input_schema: json!({ + "type":"object", + "properties": {(property): {"$ref":"#/$defs/Text"}}, + "$defs": {"Text": {"type":"string"}} + }), + output_schema: module.output_schema(), + version: "1.0.0".into(), + tags: vec![], + annotations: Some(ModuleAnnotations::default()), + examples: vec![], + metadata: std::collections::HashMap::new(), + display: None, + sunset_date: None, + dependencies: vec![], + enabled: true, + }; + registry.register(id, Box::new(module), descriptor).unwrap(); + } + + async fn discovery_http_request( + app: &axum::Router, + role: &str, + method: &str, + params: Value, + ) -> Value { + use axum::{body::Body, http::Request}; + use tower::ServiceExt; + let request = Request::builder() + .method("POST") + .uri("/mcp") + .header("content-type", "application/json") + .header("mcp-protocol-version", "2025-06-18") + .header("x-test-role", role) + .body(Body::from( + json!({ + "jsonrpc":"2.0","id":1,"method":method,"params":params + }) + .to_string(), + )) + .unwrap(); + let response = app.clone().oneshot(request).await.unwrap(); + let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + serde_json::from_slice(&bytes).unwrap() + } + + #[tokio::test] + async fn test_http_discovery_filters_tools_and_resources_for_each_identity() { + let registry = Arc::new(Registry::new()); + register_discovery_fixture(®istry, "stale"); + let mut rule = apcore::ACLRule::new( + vec!["@external".into()], + vec!["demo.governed".into(), "system.manifest.search".into()], + "allow", + ); + rule.conditions = Some(json!({"roles":["reader"]})); + let mut executor = Executor::new(Arc::clone(®istry), Config::default()); + executor.set_acl(apcore::ACL::new(vec![rule], "deny", None)); + let mut sys_config = Config::default(); + sys_config.set("sys_modules.enabled", json!(true)); + apcore::register_sys_modules(Arc::clone(®istry), &executor, &sys_config, None).unwrap(); + let mcp = APCoreMCP::builder() + .backend(BackendSource::Executor(Arc::new(executor))) + .build() + .unwrap(); + let (server, _, _, options, _, _) = mcp.build_server_components().unwrap(); + let handler = ServerHandler::from_server(&server, options).unwrap(); + let app = Arc::new(TransportManager::new(None)) + .build_streamable_http_app(Arc::new(handler), None) + .layer(crate::auth::middleware::AuthMiddlewareLayer::new(Arc::new( + DiscoveryFixtureAuth, + ))); + for role in ["observer", "reader"] { + let initialized = discovery_http_request(&app, role, "initialize", json!({ + "protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"fixture","version":"1"} + })).await; + assert!(initialized.get("result").is_some()); + } + for role in ["observer", "reader", "observer"] { + let response = discovery_http_request(&app, role, "tools/list", json!({})).await; + let tools = response["result"]["tools"].as_array().unwrap(); + assert_eq!( + tools.iter().any(|tool| tool["name"] == "demo.governed"), + role == "reader" + ); + assert!(tools.iter().any(|tool| tool["name"] + .as_str() + .is_some_and(|name| name.starts_with("__apcore_task_")))); + let resources = discovery_http_request(&app, role, "resources/list", json!({})).await; + assert_eq!( + resources["result"]["resources"] + .as_array() + .unwrap() + .iter() + .any(|resource| resource["uri"] == "docs://demo.governed"), + role == "reader" + ); + let doc = discovery_http_request( + &app, + role, + "resources/read", + json!({"uri":"docs://demo.governed"}), + ) + .await; + assert_eq!(doc.get("result").is_some(), role == "reader"); + let called = discovery_http_request( + &app, + role, + "tools/call", + json!({"name":"demo.governed", "arguments":{}}), + ) + .await; + assert_eq!(called["result"]["isError"], role != "reader"); + assert_eq!( + tools + .iter() + .any(|tool| tool["name"] == "system.manifest.search"), + role == "reader" + ); + let searched = discovery_http_request( + &app, + role, + "tools/call", + json!({"name":"system.manifest.search","arguments":{"prefix":"demo."}}), + ) + .await; + assert_eq!(searched["result"]["isError"], role != "reader"); + if role == "reader" { + let page: Value = serde_json::from_str( + searched["result"]["content"][0]["text"].as_str().unwrap(), + ) + .unwrap(); + assert_eq!(page["items"][0]["module_id"], "demo.governed"); + assert_eq!(page["next_cursor"], Value::Null); + } + } + assert!(registry.unregister("demo.governed").unwrap()); + register_discovery_fixture(®istry, "fresh"); + let listing = discovery_http_request(&app, "reader", "tools/list", json!({})).await; + let tools = listing["result"]["tools"].as_array().unwrap(); + let tool = tools + .iter() + .find(|tool| tool["name"] == "demo.governed") + .unwrap(); + assert_eq!( + tool["inputSchema"]["properties"]["fresh"]["$ref"], + "#/$defs/Text" + ); + assert!(tool["inputSchema"]["properties"].get("stale").is_none()); + let doc = discovery_http_request( + &app, + "reader", + "resources/read", + json!({"uri":"docs://demo.governed"}), + ) + .await; + assert_eq!( + doc["result"]["contents"][0]["content"], + "Current documentation: fresh" + ); + } + #[tokio::test] async fn test_governed_mcp_redacts_referenced_sensitive_output() { for draft_seven in [false, true] { diff --git a/mcp/rust/src/server/factory.rs b/mcp/rust/src/server/factory.rs index 5074e65a..a4680360 100644 --- a/mcp/rust/src/server/factory.rs +++ b/mcp/rust/src/server/factory.rs @@ -688,67 +688,7 @@ impl MCPServerFactory { } }; - // apcore 0.27 changed `Registry::describe` in two ways: it became - // fallible, and it now returns the full generated markdown - // envelope (heading, tags, parameter table) rather than the - // module's one-line summary. This slot is the NON-rich fallback of - // the chain below, so adopting the new text would make - // `rich_description: false` emit a rich document and collapse the - // flag. `descriptor.description` is the exact value 0.26's - // `describe()` returned for a registered module - // (`module.description()`), so reading it preserves that text. - let base_description = descriptor.description.clone(); - - // Resolve display overlay. apcore 0.19.0 introduced a top-level - // `ModuleDescriptor.display` field; when present, it takes - // precedence over `metadata["display"]` (kept for backwards - // compatibility with configs that embedded the overlay in metadata). - let mcp_display = descriptor - .display - .as_ref() - .or_else(|| descriptor.metadata.get("display")) - .and_then(|v| v.get("mcp")); - - let name_override = mcp_display - .and_then(|d| d.get("alias")) - .and_then(|v| v.as_str()); - - // Resolution chain for the LLM-facing description: - // 1. Operator-typed `display.mcp.description` (hard override). - // 2. apcore-toolkit `format_module(Markdown)` when - // `rich_description` is on — gives the LLM a structured - // tool description (parameters, returns, behavior table, - // tags, examples) instead of a one-line summary. - // 3. Fallback to the plain `registry.describe()` text. - let description = match mcp_display - .and_then(|d| d.get("description")) - .and_then(|v| v.as_str()) - { - Some(desc) => desc.to_string(), - // [A-D-MD-3] None from the helper means the render failed; - // fall back to the plain describe() text. - None if self.rich_description => { - crate::markdown::render_module_markdown(&descriptor, true) - .unwrap_or(base_description) - } - None => base_description, - }; - - let description = match mcp_display - .and_then(|d| d.get("guidance")) - .and_then(|v| v.as_str()) - { - Some(guidance) => format!("{}\n\nGuidance: {}", description, guidance), - None => description, - }; - - // Keep tool construction on the descriptor's runtime schema. - match self.build_tool_with_registry( - &descriptor, - &description, - name_override, - Some(registry), - ) { + match self.build_registered_tool(&descriptor) { Ok(tool) => tools.push(tool), Err(e) => { // Reserved-prefix is fatal (matched at the loop top with @@ -771,6 +711,104 @@ impl MCPServerFactory { Ok(tools) } + fn build_registered_tool( + &self, + descriptor: &ModuleDescriptor, + ) -> Result> { + // apcore 0.27 changed `Registry::describe` in two ways: it became + // fallible, and it now returns the full generated markdown + // envelope (heading, tags, parameter table) rather than the + // module's one-line summary. This slot is the NON-rich fallback of + // the chain below, so adopting the new text would make + // `rich_description: false` emit a rich document and collapse the + // flag. `descriptor.description` is the exact value 0.26's + // `describe()` returned for a registered module + // (`module.description()`), so reading it preserves that text. + let base_description = descriptor.description.clone(); + + // Resolve display overlay. apcore 0.19.0 introduced a top-level + // `ModuleDescriptor.display` field; when present, it takes + // precedence over `metadata["display"]` (kept for backwards + // compatibility with configs that embedded the overlay in metadata). + let mcp_display = descriptor + .display + .as_ref() + .or_else(|| descriptor.metadata.get("display")) + .and_then(|v| v.get("mcp")); + + let name_override = mcp_display + .and_then(|d| d.get("alias")) + .and_then(|v| v.as_str()); + + // Resolution chain for the LLM-facing description: + // 1. Operator-typed `display.mcp.description` (hard override). + // 2. apcore-toolkit `format_module(Markdown)` when + // `rich_description` is on — gives the LLM a structured + // tool description (parameters, returns, behavior table, + // tags, examples) instead of a one-line summary. + // 3. Fallback to the plain `registry.describe()` text. + let description = match mcp_display + .and_then(|d| d.get("description")) + .and_then(|v| v.as_str()) + { + Some(desc) => desc.to_string(), + // [A-D-MD-3] None from the helper means the render failed; + // fall back to the plain describe() text. + None if self.rich_description => { + crate::markdown::render_module_markdown(descriptor, true) + .unwrap_or(base_description) + } + None => base_description, + }; + + let description = match mcp_display + .and_then(|d| d.get("guidance")) + .and_then(|v| v.as_str()) + { + Some(guidance) => format!("{}\n\nGuidance: {}", description, guidance), + None => description, + }; + + self.build_tool(descriptor, &description, name_override) + } + + pub(crate) fn register_governed_tools( + &self, + server: &mut MCPServer, + router: Arc, + tools: &[Tool], + tags: Option>, + prefix: Option, + ) { + let factory = Self::with_rich_description(self.rich_description); + let meta_tools = tools + .iter() + .filter(|tool| AsyncTaskBridge::is_reserved_id(&tool.name)) + .cloned() + .collect::>(); + let fallback = server.list_tools_handler.clone(); + server.list_tools_handler = Some(Arc::new(move || { + let Some(discovery) = router.core_discovery() else { + return fallback.as_ref().map_or_else(Vec::new, |handler| handler()); + }; + let tag_refs = tags + .as_ref() + .map(|values| values.iter().map(String::as_str).collect::>()); + let mut tools = discovery + .executor + .registry() + .list(tag_refs.as_deref(), prefix.as_deref(), None) + .into_iter() + .filter(|id| !is_readonly_system_resource_module_id(id)) + .filter_map(|id| discovery.descriptor(&id)) + .filter_map(|descriptor| factory.build_registered_tool(&descriptor).ok()) + .filter(|tool| !AsyncTaskBridge::is_reserved_id(&tool.name)) + .collect::>(); + tools.extend(meta_tools.iter().cloned()); + tools + })); + } + // ---- Task: register_handlers ---- /// Register `list_tools` and `call_tool` handlers on the server. @@ -993,9 +1031,20 @@ impl MCPServerFactory { // list_resources handler let docs_for_list = Arc::clone(&docs); let available_for_list = Arc::clone(&available); + let router_for_list = Arc::clone(&router); server.list_resources_handler = Some(Arc::new(move || { - let mut resources: Vec = docs_for_list - .keys() + let ids = match router_for_list.core_discovery() { + Some(discovery) => discovery + .executor + .registry() + .module_ids() + .into_iter() + .filter(|id| discovery.documentation(id).is_some()) + .collect(), + None => docs_for_list.keys().cloned().collect::>(), + }; + let mut resources: Vec = ids + .into_iter() .map(|module_id| Resource { uri: format!("docs://{}", module_id), name: format!("{} documentation", module_id), @@ -1036,9 +1085,13 @@ impl MCPServerFactory { let available = Arc::clone(&available); Box::pin(async move { if let Some(module_id) = uri.strip_prefix("docs://") { - return match docs.get(module_id) { - Some(doc) => Ok(vec![ReadResourceContents { - content: doc.clone(), + let documentation = match router.core_discovery() { + Some(discovery) => discovery.documentation(module_id), + None => docs.get(module_id).cloned(), + }; + return match documentation { + Some(content) => Ok(vec![ReadResourceContents { + content, mime_type: "text/plain".to_string(), }]), None => Err(FactoryError::ResourceNotFound(uri.clone())), diff --git a/mcp/rust/src/server/router.rs b/mcp/rust/src/server/router.rs index 9a7a5d4b..70510e92 100644 --- a/mcp/rust/src/server/router.rs +++ b/mcp/rust/src/server/router.rs @@ -203,6 +203,14 @@ pub trait Executor: Send + Sync { None } + /// Return the Core executor and strategy in use for a governed projection. + fn discovery_executor( + &self, + _want_trace: bool, + ) -> Option<(&apcore::Executor, &apcore::ExecutionStrategy)> { + None + } + /// Return the descriptor-default version hint for `module_id`, if any. /// /// Used by [`ExecutionRouter::handle_call`] as the lowest-priority @@ -417,6 +425,29 @@ pub struct ContentItem { pub data: Value, } +pub(crate) struct CoreDiscovery<'a> { + pub(crate) executor: &'a apcore::Executor, + strategy: &'a apcore::ExecutionStrategy, + context: apcore::Context, +} + +impl CoreDiscovery<'_> { + pub(crate) fn descriptor(&self, module_id: &str) -> Option { + self.executor.get_callable_descriptor_for_strategy( + module_id, + None, + Some(&self.context), + self.strategy, + ) + } + + pub(crate) fn documentation(&self, module_id: &str) -> Option { + self.descriptor(module_id)? + .documentation + .filter(|text| !text.is_empty()) + } +} + /// Routes incoming MCP tool calls to the underlying apcore executor. pub struct ExecutionRouter { executor: Option>, @@ -489,6 +520,20 @@ impl Drop for CancelGuard { } impl ExecutionRouter { + pub(crate) fn core_discovery(&self) -> Option> { + let (executor, strategy) = self.executor.as_ref()?.discovery_executor(self.trace)?; + let context = AUTH_IDENTITY + .try_with(Clone::clone) + .ok() + .flatten() + .map_or_else(apcore::Context::anonymous, apcore::Context::new); + Some(CoreDiscovery { + executor, + strategy, + context, + }) + } + /// Create a stub router for testing. /// /// The stub router does not execute any modules. Its `handle_call` diff --git a/mcp/rust/src/server/transport.rs b/mcp/rust/src/server/transport.rs index 91fab9cb..93007589 100644 --- a/mcp/rust/src/server/transport.rs +++ b/mcp/rust/src/server/transport.rs @@ -950,22 +950,27 @@ struct StreamableHttpState { #[derive(Clone)] struct HttpSession { id: String, - owner: Option<(String, String)>, + owner: Option, requests: DirectRequests, } -fn http_session_owner() -> Option<(String, String)> { - AUTH_IDENTITY - .try_with(|owner| { - owner.as_ref().map(|identity| { - ( - identity.identity_type().to_string(), - identity.id().to_string(), - ) - }) - }) - .ok() - .flatten() +type SessionOwner = (String, String); + +fn request_identity() -> Option { + AUTH_IDENTITY.try_with(Clone::clone).ok().flatten() +} + +fn session_owner(identity: Option<&apcore::Identity>) -> Option { + identity.map(|identity| { + ( + identity.identity_type().to_owned(), + identity.id().to_owned(), + ) + }) +} + +fn http_session_owner() -> Option { + session_owner(request_identity().as_ref()) } impl StreamableHttpState { @@ -1187,25 +1192,21 @@ async fn streamable_http_delete_handler( // SSE transport state & handlers (deprecated) // --------------------------------------------------------------------------- -/// Registry of live SSE sessions: session id → that connection's inbound queue. -/// -/// Guarded by a `std::sync::Mutex` rather than tokio's: every critical section -/// is a single `HashMap` operation with no `.await` inside, and a synchronous -/// lock is what lets [`SseSessionGuard::drop`] deregister a session during a -/// panic unwind, where awaiting is impossible. -type SseSessions = - Arc>>>; - -/// Lock the session registry, recovering from a poisoned mutex. -/// -/// Poisoning carries no meaning here: the map holds channel senders, and a -/// panic mid-`insert`/`remove` cannot leave a `HashMap` in a state that a -/// later `get`/`remove` misreads. Failing every subsequent connection over it -/// would turn one panicking session into a dead transport. -fn lock_sessions( - sessions: &SseSessions, -) -> std::sync::MutexGuard<'_, std::collections::HashMap>> -{ +struct SseInbound { + message: Value, + identity: Option, +} + +struct SseSession { + owner: Option, + sender: tokio::sync::mpsc::Sender, +} + +/// Each live SSE session belongs to its authenticated stream owner. +type SseSessionMap = std::collections::HashMap; +type SseSessions = Arc>; + +fn lock_sessions(sessions: &SseSessions) -> std::sync::MutexGuard<'_, SseSessionMap> { sessions .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) @@ -1238,10 +1239,16 @@ impl SseSessionGuard { session_id: String, sessions: SseSessions, manager: Arc, - inbound_tx: tokio::sync::mpsc::Sender, + inbound_tx: tokio::sync::mpsc::Sender, session_registry: Option>, ) -> Self { - lock_sessions(&sessions).insert(session_id.clone(), inbound_tx); + lock_sessions(&sessions).insert( + session_id.clone(), + SseSession { + owner: http_session_owner(), + sender: inbound_tx, + }, + ); Self { session_id, sessions, @@ -1416,7 +1423,7 @@ async fn sse_stream_handler( let session_id = uuid::Uuid::new_v4().to_string(); // Inbound: messages posted to /messages/?sessionId=. - let (inbound_tx, mut inbound_rx) = tokio::sync::mpsc::channel::(256); + let (inbound_tx, mut inbound_rx) = tokio::sync::mpsc::channel::(256); // Outbound: the SSE frames this connection — and only this one — receives. let (event_tx, event_rx) = tokio::sync::mpsc::channel::>(256); @@ -1466,7 +1473,7 @@ async fn sse_stream_handler( // with it the receiving half of the event channel. _ = event_tx.closed() => break, inbound = inbound_rx.recv() => { - let Some(mut message) = inbound else { break }; + let Some(SseInbound { mut message, identity }) = inbound else { break }; // An answer to a server-initiated request is not a // request. It has to complete its waiter here; the // handler would see a message with no `method` and @@ -1490,9 +1497,11 @@ async fn sse_stream_handler( let requests = requests.clone(); let registration = requests.register(&message); tokio::spawn(async move { - if let Some(response) = requests.dispatch_registered( - handler.as_ref(), message, registration, Some(slots) - ).await { + let response = AUTH_IDENTITY.scope( + identity, + requests.dispatch_registered(handler.as_ref(), message, registration, Some(slots)), + ).await; + if let Some(response) = response { let data = serde_json::to_string(&response).unwrap_or_default(); let event = Event::default().event("message").data(data); let _ = event_tx.send(Ok(event)).await; @@ -1563,13 +1572,24 @@ async fn sse_messages_handler( .into_response(); }; - let sender = lock_sessions(&state.sessions).get(&session_id).cloned(); + let identity = request_identity(); + let owner = session_owner(identity.as_ref()); + let sender = lock_sessions(&state.sessions) + .get(&session_id) + .filter(|session| session.owner == owner) + .map(|session| session.sender.clone()); let Some(sender) = sender else { tracing::debug!(session_id = %session_id, "rejected sse message: unknown session"); return (StatusCode::BAD_REQUEST, "unknown session").into_response(); }; - match sender.send(body).await { + match sender + .send(SseInbound { + message: body, + identity, + }) + .await + { Ok(()) => StatusCode::ACCEPTED.into_response(), // The stream closed between lookup and send. Err(_) => { @@ -2485,6 +2505,57 @@ mod tests { tm.build_sse_app_parts(handler, None) } + #[tokio::test] + async fn sse_dispatch_rebinds_the_current_authenticated_owner() { + struct IdentityEcho; + + #[async_trait::async_trait] + impl McpHandler for IdentityEcho { + async fn handle_message(&self, message: Value) -> Option { + Some(serde_json::json!({ + "id": message["id"], + "roles": request_identity().as_ref().map(|identity| identity.roles()), + })) + } + } + + let identity = |id: &str, role: &str| { + apcore::Identity::new( + id.to_owned(), + "user".into(), + vec![role.to_owned()], + std::collections::HashMap::new(), + ) + }; + let app = sse_test_app_parts_with( + Arc::new(TransportManager::new(None)), + Arc::new(IdentityEcho), + ) + .0; + let (mut stream, session_id) = AUTH_IDENTITY + .scope(Some(identity("user", "previous")), open_sse_session(&app)) + .await; + let denied = AUTH_IDENTITY + .scope( + Some(identity("other-user", "different")), + post_sse_message(&app, &session_id, 1), + ) + .await; + assert_eq!(denied, StatusCode::BAD_REQUEST); + let accepted = AUTH_IDENTITY + .scope( + Some(identity("user", "current")), + post_sse_message(&app, &session_id, 2), + ) + .await; + assert_eq!(accepted, StatusCode::ACCEPTED); + let responses = collect_sse_responses(&mut stream, 1).await; + assert_eq!( + responses, + vec![serde_json::json!({"id":2,"roles":["current"]})] + ); + } + #[tokio::test] async fn sse_messages_post_returns_202_for_a_live_session() { let app = sse_test_app(); @@ -2887,7 +2958,7 @@ mod tests { // The panic message this prints to stderr is expected. let sessions: SseSessions = Arc::new(std::sync::Mutex::new(Default::default())); let (tm, cancelled) = recording_transport_manager(); - let (inbound_tx, _inbound_rx) = tokio::sync::mpsc::channel::(1); + let (inbound_tx, _inbound_rx) = tokio::sync::mpsc::channel::(1); let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { let _guard = SseSessionGuard::register( diff --git a/mcp/typescript/README.md b/mcp/typescript/README.md index 1301b290..9001b4eb 100644 --- a/mcp/typescript/README.md +++ b/mcp/typescript/README.md @@ -17,6 +17,13 @@ additional-property restrictions still apply. Factory `strict` options are retai for compatibility and do not project OpenAI strict schemas onto MCP. OpenAI tool exports and standalone SchemaConverter APIs retain their existing behavior. +Core-backed MCP servers apply caller-aware discovery to `tools/list` and +`docs://` resource listing and reads. The server uses each request's trusted +identity and the active Core ACL. A known tool call still goes through normal +execution authorization. A custom executor can opt into this projection by +implementing `getCallableDescriptor`; custom executors without this API keep +their existing catalog behavior. + ## Features diff --git a/mcp/typescript/package.json b/mcp/typescript/package.json index 53d20d52..761ad74a 100644 --- a/mcp/typescript/package.json +++ b/mcp/typescript/package.json @@ -51,7 +51,7 @@ "dependencies": { "@modelcontextprotocol/sdk": "1.32.0", "ajv": "^8.17.1", - "apcore-js": "1.0.0-alpha.3", + "apcore-js": "1.0.0-alpha.4", "apcore-toolkit": "0.15.1-alpha.2", "jsonwebtoken": ">=9.0.3", "mcp-embedded-ui": ">=0.5.1" diff --git a/mcp/typescript/pnpm-lock.yaml b/mcp/typescript/pnpm-lock.yaml index 77e15c81..afb3c6f3 100644 --- a/mcp/typescript/pnpm-lock.yaml +++ b/mcp/typescript/pnpm-lock.yaml @@ -15,8 +15,8 @@ importers: specifier: ^8.17.1 version: 8.20.0 apcore-js: - specifier: 1.0.0-alpha.3 - version: 1.0.0-alpha.3(typescript@5.9.3) + specifier: 1.0.0-alpha.4 + version: 1.0.0-alpha.4(typescript@5.9.3) apcore-toolkit: specifier: 0.15.1-alpha.2 version: 0.15.1-alpha.2(@sinclair/typebox@0.34.48)(typescript@5.9.3) @@ -619,8 +619,8 @@ packages: resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} engines: {node: '>=8'} - apcore-js@1.0.0-alpha.3: - resolution: {integrity: sha512-0zv5xlVunNaa7GhbeJsgG0q6Dd97+f3T/kFrRyhzIkVc957aX87bhWLMlhgqhg/4iFZ1ZWDXl15kxOE1xbCPqw==} + apcore-js@1.0.0-alpha.4: + resolution: {integrity: sha512-Ix49EPRQBVezM4mp59wGNW3AI7RFvD1I9iwPoYp/F81/gUZQIJ1CLjQkcFsiNME14EIGmcLL+noa/ttVg6qIcQ==} engines: {node: '>=20.0.0'} peerDependencies: typescript: ^5.5.0 @@ -1938,7 +1938,7 @@ snapshots: dependencies: color-convert: 2.0.1 - apcore-js@1.0.0-alpha.3(typescript@5.9.3): + apcore-js@1.0.0-alpha.4(typescript@5.9.3): dependencies: '@sinclair/typebox': 0.34.48 js-yaml: 4.3.2 @@ -1950,7 +1950,7 @@ snapshots: dependencies: '@sinclair/typebox': 0.34.48 ajv: 8.20.0 - apcore-js: 1.0.0-alpha.3(typescript@5.9.3) + apcore-js: 1.0.0-alpha.4(typescript@5.9.3) js-yaml: 4.3.2 transitivePeerDependencies: - typescript diff --git a/mcp/typescript/src/server/factory.ts b/mcp/typescript/src/server/factory.ts index a86f35cd..3ac333c0 100644 --- a/mcp/typescript/src/server/factory.ts +++ b/mcp/typescript/src/server/factory.ts @@ -108,6 +108,7 @@ export interface MCPServerFactoryOptions { export class MCPServerFactory { private readonly _annotationMapper: AnnotationMapper; private readonly _richDescription: boolean; + private readonly _toolSources = new WeakMap(); private _warnedToolkitMissing = false; constructor(options: MCPServerFactoryOptions = {}) { @@ -332,6 +333,11 @@ export class MCPServerFactory { (tool as Tool & { _meta?: Record })._meta = meta; } + const hint = metadata.versionHint; + this._toolSources.set(tool, { + moduleId: descriptor.moduleId, + versionHint: typeof hint === "string" ? hint : undefined, + }); return tool; } @@ -421,7 +427,7 @@ export class MCPServerFactory { * for the three per-module read-only management modules * ({@link SYSTEM_TEMPLATE_RESOURCE_MODULES}) — only when registered, * and only registered at all when at least one is present. - * - resources/read: dispatches `docs://` by static lookup (unchanged), + * - resources/read: resolves `docs://` through the caller-aware backend, * and `apcore://` management URIs by parsing the module id + params * ({@link parseSystemResourceUri}) and calling `router.handleCall()` — * the SAME ACL/approval/audit pipeline as `tools/call`. Management @@ -476,7 +482,9 @@ export class MCPServerFactory { // Handle resources/list requests server.setRequestHandler(ListResourcesRequestSchema, async () => { const resources: Resource[] = []; - for (const [moduleId, _doc] of docsMap) { + const resolve = router?.discoveryResolver?.(); + for (const moduleId of docsMap.keys()) { + if (resolve && !resolve(moduleId)?.documentation) continue; resources.push({ uri: `docs://${moduleId}`, name: `${moduleId} documentation`, @@ -590,8 +598,11 @@ export class MCPServerFactory { throw new Error(`Unsupported URI scheme: ${uri}`); } const moduleId = uri.slice(prefix.length); - const documentation = docsMap.get(moduleId); - if (documentation === undefined) { + const resolve = router?.discoveryResolver?.(); + const documentation = docsMap.has(moduleId) + ? (resolve ? resolve(moduleId)?.documentation : docsMap.get(moduleId)) + : undefined; + if (!documentation) { throw new Error(`Resource not found: ${uri}`); } const result: ReadResourceResult = { @@ -607,6 +618,29 @@ export class MCPServerFactory { }); } + private _visibleTools( + tools: readonly Tool[], + resolve: (moduleId: string, versionHint?: string) => ModuleDescriptor | null, + ): Tool[] { + const visible: Tool[] = []; + for (const tool of tools) { + const source = this._toolSources.get(tool); + if (!source && tool.name.startsWith(APCORE_META_TOOL_PREFIX)) { + visible.push(tool); + continue; + } + const descriptor = resolve(source?.moduleId ?? tool.name, source?.versionHint); + if (descriptor === null) continue; + try { + // Keep the registered MCP name while projecting the live definition. + visible.push({ ...this.buildTool(descriptor), name: tool.name }); + } catch { + // A replacement may no longer have an MCP-compatible schema. + } + } + return visible; + } + /** * Register tools/list and tools/call request handlers on a Server instance. * @@ -639,7 +673,9 @@ export class MCPServerFactory { // Handle tools/list requests server.setRequestHandler(ListToolsRequestSchema, async (_request, extra) => { - const listedTools = supportsStructuredOutput(server, extra) ? allTools : allTools.map(tool => { + const resolve = router.discoveryResolver?.(); + const visibleTools = resolve ? this._visibleTools(allTools, resolve) : allTools; + const listedTools = supportsStructuredOutput(server, extra) ? visibleTools : visibleTools.map(tool => { const { outputSchema: _outputSchema, ...legacyTool } = tool; return legacyTool; }); @@ -655,6 +691,7 @@ export class MCPServerFactory { if (!tool) { throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${name}`); } + const moduleId = this._toolSources.get(tool)?.moduleId ?? name; const toolArgs = (args ?? {}) as Record; // Build HandleCallExtra from MCP SDK extra @@ -731,13 +768,13 @@ export class MCPServerFactory { } const reply: ApprovalReplyCapture | undefined = approvalBridge - ? { moduleId: name, confirmed: false } + ? { moduleId, confirmed: false } : undefined; handleCallExtra.approvalReply = reply; let approval: PendingApprovalReply | undefined; let callResult: Awaited>; try { - callResult = await router.handleCall(name, toolArgs, handleCallExtra); + callResult = await router.handleCall(moduleId, toolArgs, handleCallExtra); if (reply?.confirmed) approval = reply.candidate; } finally { if (reply) delete reply.candidate; diff --git a/mcp/typescript/src/server/router.ts b/mcp/typescript/src/server/router.ts index fdea8e35..eb954b88 100644 --- a/mcp/typescript/src/server/router.ts +++ b/mcp/typescript/src/server/router.ts @@ -16,7 +16,7 @@ import { confirmPendingApproval, runApprovalInvocation, type ApprovalReplyCaptur import type { Module } from "apcore-js"; import { ErrorMapper } from "../adapters/errors.js"; import { ErrorCodes } from "../types.js"; -import type { Executor, TextContentDict, McpErrorResponse, StreamCompletion, StreamExecution, StreamStepOutcome } from "../types.js"; +import type { Executor, ModuleDescriptor, TextContentDict, McpErrorResponse, StreamCompletion, StreamExecution, StreamStepOutcome } from "../types.js"; import { createBridgeContext } from "./context.js"; import { MCP_PROGRESS_KEY, MCP_ELICIT_KEY } from "../helpers.js"; import type { ElicitResult } from "../helpers.js"; @@ -491,6 +491,15 @@ export class ExecutionRouter { } } + /** Use the invocation backend and trusted transport identity for one discovery request. */ + discoveryResolver(): ((moduleId: string, versionHint?: string) => ModuleDescriptor | null) | undefined { + const backend = this._executor; + const lookup = backend.getCallableDescriptor; + if (typeof lookup !== "function") return undefined; + const context = createBridgeContext({}, getCurrentIdentity()); + return (moduleId, versionHint) => lookup.call(backend, moduleId, context, versionHint); + } + private async _handleCallInner( toolName: string, args: Record, diff --git a/mcp/typescript/src/types.ts b/mcp/typescript/src/types.ts index 214e5beb..ed4dcb0d 100644 --- a/mcp/typescript/src/types.ts +++ b/mcp/typescript/src/types.ts @@ -126,6 +126,8 @@ export interface Registry { export interface Executor { registry: Registry; + /** Resolve a live descriptor through Core discovery for an authenticated request. */ + getCallableDescriptor?(moduleId: string, context?: unknown, versionHint?: string): ModuleDescriptor | null; call(moduleId: string, inputs: Record, context?: unknown, versionHint?: string): Promise>; callAsync?(moduleId: string, inputs: Record, context?: unknown, versionHint?: string): Promise>; stream?(moduleId: string, inputs: Record, context?: unknown, versionHint?: string): AsyncIterable>; diff --git a/mcp/typescript/tests/server/capability-discovery.test.ts b/mcp/typescript/tests/server/capability-discovery.test.ts new file mode 100644 index 00000000..22ca04ab --- /dev/null +++ b/mcp/typescript/tests/server/capability-discovery.test.ts @@ -0,0 +1,111 @@ +import { once } from "node:events"; +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import { ACL, createAnnotations, createIdentity, Executor, Registry } from "apcore-js"; +import { expect, it, vi } from "vitest"; + +import { asyncServe } from "../../src/index.js"; + +const moduleId = "example.limited"; +const alias = "reader_example"; +const inputSchema = { + type: "object", + properties: { message: { $ref: "#/$defs/message" } }, + required: ["message"], + $defs: { message: { type: "string" } }, + additionalProperties: false, +}; + +it("lists the authorized caller's tools and documentation from the live Core registration", async () => { + const registry = new Registry(); + const execute = vi.fn(() => ({ ok: true })); + async function register(documentation: string, schema = inputSchema, version = "1.1.0"): Promise { + await registry.register(moduleId, { + description: "A role-scoped module", + inputSchema: schema, + outputSchema: { type: "object" }, + annotations: createAnnotations({ readonly: true }), + execute, + }, version, { documentation, display: { mcp: { alias } }, versionHint: "1.1.0" }); + } + await register("Initial documentation"); + await registry.register("example.hidden", { + description: "Not discoverable", + inputSchema, + outputSchema: { type: "object" }, + annotations: createAnnotations({ discoverable: false }), + execute, + }, "1.0.0", { documentation: "Hidden documentation" }); + + const audit = vi.fn(); + const acl = new ACL([{ + callers: ["@external"], targets: ["example.*"], description: "", effect: "allow", + conditions: { roles: ["reader"] }, + }], "deny", audit); + const executor = new Executor({ registry, acl }); + const reader = createIdentity("reader", "user", ["reader"]); + const observer = createIdentity("observer", "user", ["observer"]); + const app = await asyncServe(executor as never, { + async: false, + authenticator: { + authenticate: async (headers): Promise => { + if (headers.authorization === "Bearer fixture-reader") return reader; + if (headers.authorization === "Bearer fixture-observer") return observer; + return null; + }, + }, + }); + const server = createServer(app.handler); + const client = new Client({ name: "capability-discovery", version: "1" }); + let token = "fixture-observer"; + try { + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const url = new URL(`http://127.0.0.1:${(server.address() as AddressInfo).port}/mcp`); + await client.connect(new StreamableHTTPClientTransport(url, { + fetch: (input, init) => { + const headers = new Headers(init?.headers); + headers.set("Authorization", `Bearer ${token}`); + return fetch(input, { ...init, headers }); + }, + })); + + expect((await client.listTools()).tools).toEqual([]); + expect((await client.listResources()).resources).toEqual([]); + await expect(client.readResource({ uri: `docs://${moduleId}` })).rejects.toThrow(/resource not found/i); + token = "fixture-reader"; + expect((await client.listTools()).tools).toMatchObject([{ name: alias, inputSchema }]); + expect((await client.listResources()).resources).toMatchObject([{ uri: `docs://${moduleId}` }]); + expect((await client.readResource({ uri: `docs://${moduleId}` })).contents) + .toMatchObject([{ text: "Initial documentation" }]); + expect(audit).not.toHaveBeenCalled(); + expect(execute).not.toHaveBeenCalled(); + + expect(await registry.safeUnregister(moduleId)).toBe(true); + const replacement = { ...inputSchema, $defs: { message: { type: "string", minLength: 2 } } }; + await register("Replacement documentation", replacement); + expect((await client.listTools()).tools).toMatchObject([{ name: alias, inputSchema: replacement }]); + expect((await client.readResource({ uri: `docs://${moduleId}` })).contents) + .toMatchObject([{ text: "Replacement documentation" }]); + token = "fixture-observer"; + expect((await client.listTools()).tools).toEqual([]); + + const forbidden = await client.callTool({ name: alias, arguments: { message: "hello" } }); + expect(forbidden.isError).toBe(true); + token = "fixture-reader"; + const allowed = await client.callTool({ name: alias, arguments: { message: "hello" } }); + expect(allowed.structuredContent).toEqual({ ok: true }); + expect(audit).toHaveBeenCalledTimes(2); + expect(execute).toHaveBeenCalledTimes(1); + + expect(await registry.safeUnregister(moduleId)).toBe(true); + await register("Different registered version", replacement, "2.0.0"); + expect((await client.listTools()).tools).toEqual([]); + } finally { + await client.close(); + await app.close(); + await new Promise(resolve => server.close(() => resolve())); + } +}); diff --git a/toolkit/python/pyproject.toml b/toolkit/python/pyproject.toml index a8103e26..faf3634d 100644 --- a/toolkit/python/pyproject.toml +++ b/toolkit/python/pyproject.toml @@ -23,7 +23,7 @@ keywords = [ "toolkit", ] dependencies = [ - "apcore>=0.33.0,<=1.0.0a3", + "apcore>=0.33.0,<=1.0.0a4", "pydantic>=2.0", "PyYAML>=6.0", ] diff --git a/toolkit/rust/Cargo.lock b/toolkit/rust/Cargo.lock index 466d32d2..1089111d 100644 --- a/toolkit/rust/Cargo.lock +++ b/toolkit/rust/Cargo.lock @@ -48,9 +48,9 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "apcore" -version = "1.0.0-alpha.3" +version = "1.0.0-alpha.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2813101192ceac629d58114dfafd4f6b519eb7dea2313cb253e1410a2ac52f65" +checksum = "412082f3f58f5a59165f20e1df00f7191b5e382ea59f2369eb486f963cb7d604" dependencies = [ "async-stream", "async-trait", diff --git a/toolkit/rust/Cargo.toml b/toolkit/rust/Cargo.toml index 9a995417..0a02e231 100644 --- a/toolkit/rust/Cargo.toml +++ b/toolkit/rust/Cargo.toml @@ -21,7 +21,7 @@ all-features = true rustdoc-args = ["--cfg", "docsrs"] [dependencies] -apcore = { version = ">=0.33.0, <=1.0.0-alpha.3", default-features = false } +apcore = { version = ">=0.33.0, <=1.0.0-alpha.4", default-features = false } serde = { version = "1", features = ["derive"] } # `preserve_order` is required for the toolkit's byte-equivalent tabular # formatters (csv / jsonl): object key order MUST match insertion order to diff --git a/toolkit/typescript/package.json b/toolkit/typescript/package.json index 403684b7..127e8927 100644 --- a/toolkit/typescript/package.json +++ b/toolkit/typescript/package.json @@ -57,7 +57,7 @@ }, "dependencies": { "ajv": "^8.17.0", - "apcore-js": ">=0.33.0 <1.0.0 || 1.0.0-alpha.2 || 1.0.0-alpha.3", + "apcore-js": ">=0.33.0 <1.0.0 || 1.0.0-alpha.2 || 1.0.0-alpha.3 || 1.0.0-alpha.4", "js-yaml": "^4.3.2" }, "peerDependencies": { diff --git a/toolkit/typescript/pnpm-lock.yaml b/toolkit/typescript/pnpm-lock.yaml index 2e362988..02e91f82 100644 --- a/toolkit/typescript/pnpm-lock.yaml +++ b/toolkit/typescript/pnpm-lock.yaml @@ -15,7 +15,7 @@ importers: specifier: ^8.17.0 version: 8.20.0 apcore-js: - specifier: '>=0.33.0 <1.0.0 || 1.0.0-alpha.2 || 1.0.0-alpha.3' + specifier: '>=0.33.0 <1.0.0 || 1.0.0-alpha.2 || 1.0.0-alpha.3 || 1.0.0-alpha.4' version: 0.33.0 js-yaml: specifier: ^4.3.2 From 9e8d90054b43eb7a1e4a672f7759289eaf8de069 Mon Sep 17 00:00:00 2001 From: tercel Date: Sat, 28 Nov 2026 02:27:42 +0800 Subject: [PATCH 2/5] fix(mcp): bind output projection to the live registration Signed-off-by: tercel --- mcp/python/src/apcore_mcp/server/router.py | 18 ++- .../tests/server/test_capability_discovery.py | 9 ++ mcp/rust/src/apcore_mcp.rs | 90 +++++++++++--- mcp/rust/src/server/factory.rs | 45 +++---- mcp/rust/src/server/router.rs | 116 +++++++++++++++++- mcp/typescript/src/server/factory.ts | 17 ++- mcp/typescript/src/server/router.ts | 44 +++++-- mcp/typescript/src/types.ts | 2 + .../tests/server/capability-discovery.test.ts | 36 +++++- 9 files changed, 310 insertions(+), 67 deletions(-) diff --git a/mcp/python/src/apcore_mcp/server/router.py b/mcp/python/src/apcore_mcp/server/router.py index 5cc3d6c5..dd0c8ce3 100644 --- a/mcp/python/src/apcore_mcp/server/router.py +++ b/mcp/python/src/apcore_mcp/server/router.py @@ -262,17 +262,23 @@ def _select_wire_version( def _output_projection( self, tool_name: str, version_hint: str | None ) -> tuple[str | None, dict[str, Any] | None]: - if not self._redact_output or not self._core_backend or version_hint is None: + if not self._redact_output or not self._core_backend: return version_hint, None registry = self._executor.registry definition = registry.get_definition(tool_name, version_hint) if definition is None: - raise ModuleError("MODULE_NOT_FOUND", f"Module '{tool_name}' not found") - # Pin only when Core can report the actual selected version. Direct - # router callers can still pass the original range to older Core. - if _matches_registered_version(registry, tool_name, version_hint, definition.version): + if version_hint is not None: + raise ModuleError("MODULE_NOT_FOUND", f"Module '{tool_name}' not found") + # Let Core report its ordinary lookup error without falling back + # to output metadata from a removed registration. + return None, {} + # Resolve redaction against the current registered schema, even if the + # default version string stayed fixed during a replacement. + if version_hint is not None and _matches_registered_version( + registry, tool_name, version_hint, definition.version, + ): version_hint = definition.version - return version_hint, definition.output_schema + return version_hint, definition.output_schema or {} def _format_result(self, result: Any) -> str: """Format an execution result into text for LLM consumption. diff --git a/mcp/python/tests/server/test_capability_discovery.py b/mcp/python/tests/server/test_capability_discovery.py index 3ccf9336..d6640fb3 100644 --- a/mcp/python/tests/server/test_capability_discovery.py +++ b/mcp/python/tests/server/test_capability_discovery.py @@ -113,9 +113,18 @@ async def test_discovery_reads_the_current_same_version_registration() -> None: "required": ["label"], } replacement.input_schema = replacement_schema + replacement.output_schema = { + "type": "object", + "properties": {"label": {"type": "string", "x-sensitive": True}}, + "required": ["label"], + } registry.register(module_id, replacement, version="1.0.0", metadata={"documentation": "Updated content."}) current = (await session.list_tools()).tools[0] assert current.inputSchema == replacement_schema resource = await session.read_resource(f"docs://{module_id}") assert resource.contents[0].text == "Updated content." + result = await session.call_tool(module_id, {"label": "private fixture output"}) + assert not result.isError + assert result.structuredContent is not None + assert "private fixture output" not in result.model_dump_json() diff --git a/mcp/rust/src/apcore_mcp.rs b/mcp/rust/src/apcore_mcp.rs index 5f816313..7f868495 100644 --- a/mcp/rust/src/apcore_mcp.rs +++ b/mcp/rust/src/apcore_mcp.rs @@ -583,9 +583,11 @@ impl APCoreMCP { .map(|t| t.iter().map(|s| s.as_str()).collect()); let tags_slice: Option<&[&str]> = tags_refs.as_deref(); let prefix = self.config.prefix.as_deref(); - let tools = factory - .build_tools(self.reg(), tags_slice, prefix) - .map_err(|e| APCoreMCPError::ServerError(e.to_string()))?; + let (tool_ids, tools): (Vec<_>, Vec<_>) = factory + .build_tools_with_ids(self.reg(), tags_slice, prefix) + .map_err(|e| APCoreMCPError::ServerError(e.to_string()))? + .into_iter() + .unzip(); // Build output schema map for output redaction. let output_schema_map: std::collections::HashMap = { @@ -655,13 +657,7 @@ impl APCoreMCP { // Register handlers factory.register_handlers(&mut server, tools.clone(), Arc::clone(&router)); - factory.register_governed_tools( - &mut server, - Arc::clone(&router), - &tools, - self.config.tags.clone(), - self.config.prefix.clone(), - ); + factory.register_governed_tools(&mut server, Arc::clone(&router), &tools, tool_ids); // Register resource handlers. Reads dispatch through `router` so the // system.* resources added by #15(a) get the same ACL / approval / @@ -2698,9 +2694,38 @@ mod tests { } } - fn register_discovery_fixture(registry: &Registry, property: &str) { - let id = "demo.governed"; - let module = MockModule::new("Governed tool"); + struct DiscoveryFixtureModule(String); + + #[async_trait::async_trait] + impl Module for DiscoveryFixtureModule { + fn description(&self) -> &str { + "Governed tool" + } + + fn input_schema(&self) -> Value { + json!({"type":"object"}) + } + + fn output_schema(&self) -> Value { + json!({ + "type": "object", + "properties": {(&self.0): {"type": "string", "x-sensitive": true}}, + "required": [&self.0], + "additionalProperties": false + }) + } + + async fn execute( + &self, + _: Value, + _: &apcore::Context, + ) -> Result { + Ok(json!({(&self.0): "local-redaction-fixture"})) + } + } + + fn register_discovery_fixture(registry: &Registry, id: &str, property: &str) { + let module = DiscoveryFixtureModule(property.to_owned()); let descriptor = ModuleDescriptor { module_id: id.into(), name: None, @@ -2756,10 +2781,10 @@ mod tests { #[tokio::test] async fn test_http_discovery_filters_tools_and_resources_for_each_identity() { let registry = Arc::new(Registry::new()); - register_discovery_fixture(®istry, "stale"); + register_discovery_fixture(®istry, "demo.governed", "stale"); let mut rule = apcore::ACLRule::new( vec!["@external".into()], - vec!["demo.governed".into(), "system.manifest.search".into()], + vec!["demo.*".into(), "system.manifest.search".into()], "allow", ); rule.conditions = Some(json!({"roles":["reader"]})); @@ -2844,9 +2869,25 @@ mod tests { } } assert!(registry.unregister("demo.governed").unwrap()); - register_discovery_fixture(®istry, "fresh"); + register_discovery_fixture(®istry, "demo.governed", "fresh"); + register_discovery_fixture(®istry, "demo.unpublished", "new"); let listing = discovery_http_request(&app, "reader", "tools/list", json!({})).await; let tools = listing["result"]["tools"].as_array().unwrap(); + assert!(!tools.iter().any(|tool| tool["name"] == "demo.unpublished")); + let docs = discovery_http_request(&app, "reader", "resources/list", json!({})).await; + assert!(!docs["result"]["resources"] + .as_array() + .unwrap() + .iter() + .any(|resource| resource["uri"] == "docs://demo.unpublished")); + let unknown_doc = discovery_http_request( + &app, + "reader", + "resources/read", + json!({"uri":"docs://demo.unpublished"}), + ) + .await; + assert!(unknown_doc.get("error").is_some()); let tool = tools .iter() .find(|tool| tool["name"] == "demo.governed") @@ -2856,6 +2897,23 @@ mod tests { "#/$defs/Text" ); assert!(tool["inputSchema"]["properties"].get("stale").is_none()); + assert_eq!(tool["outputSchema"]["required"], json!(["fresh"])); + let response = discovery_http_request( + &app, + "reader", + "tools/call", + json!({"name":"demo.governed","arguments":{}}), + ) + .await; + let result = &response["result"]; + let safe = json!({"fresh": apcore::executor::REDACTED_VALUE}); + assert_eq!(result["isError"], false, "{result}"); + assert_eq!(result["structuredContent"], safe); + assert_eq!( + serde_json::from_str::(result["content"][0]["text"].as_str().unwrap()).unwrap(), + safe + ); + assert!(!response.to_string().contains("local-redaction-fixture")); let doc = discovery_http_request( &app, "reader", diff --git a/mcp/rust/src/server/factory.rs b/mcp/rust/src/server/factory.rs index a4680360..6aee8305 100644 --- a/mcp/rust/src/server/factory.rs +++ b/mcp/rust/src/server/factory.rs @@ -657,6 +657,16 @@ impl MCPServerFactory { tags: Option<&[&str]>, prefix: Option<&str>, ) -> Result, crate::server::server::FactoryError> { + self.build_tools_with_ids(registry, tags, prefix) + .map(|tools| tools.into_iter().map(|(_, tool)| tool).collect()) + } + + pub(crate) fn build_tools_with_ids( + &self, + registry: &Registry, + tags: Option<&[&str]>, + prefix: Option<&str>, + ) -> Result, FactoryError> { let module_ids = registry.list(tags, prefix, None); let mut tools = Vec::new(); @@ -689,7 +699,7 @@ impl MCPServerFactory { }; match self.build_registered_tool(&descriptor) { - Ok(tool) => tools.push(tool), + Ok(tool) => tools.push((module_id, tool)), Err(e) => { // Reserved-prefix is fatal (matched at the loop top with // an early return). Other build_tool errors are @@ -777,8 +787,7 @@ impl MCPServerFactory { server: &mut MCPServer, router: Arc, tools: &[Tool], - tags: Option>, - prefix: Option, + module_ids: Vec, ) { let factory = Self::with_rich_description(self.rich_description); let meta_tools = tools @@ -791,16 +800,9 @@ impl MCPServerFactory { let Some(discovery) = router.core_discovery() else { return fallback.as_ref().map_or_else(Vec::new, |handler| handler()); }; - let tag_refs = tags - .as_ref() - .map(|values| values.iter().map(String::as_str).collect::>()); - let mut tools = discovery - .executor - .registry() - .list(tag_refs.as_deref(), prefix.as_deref(), None) - .into_iter() - .filter(|id| !is_readonly_system_resource_module_id(id)) - .filter_map(|id| discovery.descriptor(&id)) + let mut tools = module_ids + .iter() + .filter_map(|id| discovery.descriptor(id)) .filter_map(|descriptor| factory.build_registered_tool(&descriptor).ok()) .filter(|tool| !AsyncTaskBridge::is_reserved_id(&tool.name)) .collect::>(); @@ -876,9 +878,9 @@ impl MCPServerFactory { .and_then(|id| router.session_registry().get(id)) .is_some_and(|session| session.supports_structured_results()); let extra_ref = extra.as_ref(); - let ((content_items, is_error, trace_id), pending) = + let (((content_items, is_error, trace_id), schema), pending) = crate::server::approval_bridge::capture_pending_approval( - router.handle_call(&name, &arguments, extra_ref), + router.handle_call_with_output_schema(&name, &arguments, extra_ref), ) .await; @@ -938,7 +940,7 @@ impl MCPServerFactory { meta, }; if structured { - result.with_structured_content(output_schemas.get(&name)) + result.with_structured_content(schema.select(output_schemas.get(&name))) } else { result } @@ -1034,12 +1036,10 @@ impl MCPServerFactory { let router_for_list = Arc::clone(&router); server.list_resources_handler = Some(Arc::new(move || { let ids = match router_for_list.core_discovery() { - Some(discovery) => discovery - .executor - .registry() - .module_ids() - .into_iter() + Some(discovery) => docs_for_list + .keys() .filter(|id| discovery.documentation(id).is_some()) + .cloned() .collect(), None => docs_for_list.keys().cloned().collect::>(), }; @@ -1085,6 +1085,9 @@ impl MCPServerFactory { let available = Arc::clone(&available); Box::pin(async move { if let Some(module_id) = uri.strip_prefix("docs://") { + if !docs.contains_key(module_id) { + return Err(FactoryError::ResourceNotFound(uri)); + } let documentation = match router.core_discovery() { Some(discovery) => discovery.documentation(module_id), None => docs.get(module_id).cloned(), diff --git a/mcp/rust/src/server/router.rs b/mcp/rust/src/server/router.rs index 70510e92..30762a7f 100644 --- a/mcp/rust/src/server/router.rs +++ b/mcp/rust/src/server/router.rs @@ -426,7 +426,7 @@ pub struct ContentItem { } pub(crate) struct CoreDiscovery<'a> { - pub(crate) executor: &'a apcore::Executor, + executor: &'a apcore::Executor, strategy: &'a apcore::ExecutionStrategy, context: apcore::Context, } @@ -448,6 +448,30 @@ impl CoreDiscovery<'_> { } } +struct LiveCallOutput { + registration: Option>, + schema: Option, + advertise: bool, +} + +tokio::task_local! { + static LIVE_CALL_OUTPUT: Arc; +} + +pub(crate) enum WireOutputSchema { + Configured, + Live(Option), +} + +impl WireOutputSchema { + pub(crate) fn select<'a>(&'a self, configured: Option<&'a Value>) -> Option<&'a Value> { + match self { + Self::Configured => configured, + Self::Live(schema) => schema.as_ref(), + } + } +} + /// Routes incoming MCP tool calls to the underlying apcore executor. pub struct ExecutionRouter { executor: Option>, @@ -850,6 +874,39 @@ impl ExecutionRouter { redacted } + fn live_call_output(&self, name: &str) -> Option { + if AsyncTaskBridge::is_reserved_id(name) { + return None; + } + let (executor, _) = self.executor.as_ref()?.discovery_executor(self.trace)?; + let registry = executor.registry(); + // This is internal execution metadata. A caller may know and invoke an + // unlisted ID, in which case Core still makes the actual ACL decision. + let registration = registry.get(name).ok().flatten(); + let descriptor = registry.get_definition(name).ok().flatten(); + let advertise = descriptor.as_ref().is_some_and(|descriptor| { + descriptor.output_schema["type"] == "object" + && !AsyncTaskBridge::is_async_module_descriptor(descriptor) + }); + let schema = descriptor.map(|descriptor| descriptor.output_schema); + Some(LiveCallOutput { + registration, + schema, + advertise, + }) + } + + fn current_call_output(&self, name: &str) -> bool { + LIVE_CALL_OUTPUT + .try_with(|binding| { + let (current, _) = self.executor.as_ref()?.discovery_executor(self.trace)?; + let registration = current.registry().get(name).ok().flatten()?; + let selected = binding.registration.as_ref()?; + Arc::ptr_eq(selected, ®istration).then_some(()) + }) + .map_or(true, |matched| matched.is_some()) + } + /// Redact sensitive fields from tool output before formatting. /// /// If `redact_output` is enabled and an output schema is registered for @@ -860,6 +917,14 @@ impl ExecutionRouter { if !self.redact_output { return result.clone(); } + if let Ok(redacted) = LIVE_CALL_OUTPUT.try_with(|output| { + output.schema.as_ref().map_or_else( + || result.clone(), + |schema| apcore::redact_sensitive(result, schema), + ) + }) { + return redacted; + } match self.output_schemas.get(tool_name) { Some(schema) => apcore::redact_sensitive(result, schema), None => result.clone(), @@ -1014,6 +1079,42 @@ impl ExecutionRouter { arguments: &Value, extra: Option<&Value>, ) -> (Vec, bool, Option) { + self.handle_call_with_output_schema(tool_name, arguments, extra) + .await + .0 + } + + pub(crate) async fn handle_call_with_output_schema( + &self, + tool_name: &str, + arguments: &Value, + extra: Option<&Value>, + ) -> (StreamOutcome, WireOutputSchema) { + let Some(output) = self.live_call_output(tool_name).map(Arc::new) else { + return ( + self.dispatch_call(tool_name, arguments, extra).await, + WireOutputSchema::Configured, + ); + }; + let result = LIVE_CALL_OUTPUT + .scope(Arc::clone(&output), async { + let outcome = self.dispatch_call(tool_name, arguments, extra).await; + if !outcome.1 && !self.current_call_output(tool_name) { + return Self::changed_registration(); + } + outcome + }) + .await; + let schema = output.advertise.then(|| output.schema.clone()).flatten(); + (result, WireOutputSchema::Live(schema)) + } + + async fn dispatch_call( + &self, + tool_name: &str, + arguments: &Value, + extra: Option<&Value>, + ) -> StreamOutcome { if Self::has_approval_input(tool_name, arguments) { return Self::stream_error("Approval credentials belong in request metadata".into()); } @@ -1759,6 +1860,9 @@ impl ExecutionRouter { ) -> (Vec, bool, Option) { match outcome { Ok((result, trace)) => { + if !self.current_call_output(tool_name) { + return Self::changed_registration(); + } let redacted_result = self.redact_output(tool_name, &result); let text = self.format_result(&redacted_result); let mut content = vec![ContentItem { @@ -2120,6 +2224,9 @@ impl ExecutionRouter { // value is later redacted. Mirrors Python's // _handle_stream invariant. [A-D-003] if let Some((progress_token, send_notification)) = progress { + if !self.current_call_output(tool_name) { + return Self::changed_registration(); + } let safe_chunk = self.redact_output(tool_name, &chunk); let notification = serde_json::json!({ "method": "notifications/progress", @@ -2176,6 +2283,9 @@ impl ExecutionRouter { }; accumulated = output; } + if !self.current_call_output(tool_name) { + return Self::changed_registration(); + } let redacted_accumulated = self.redact_output(tool_name, &accumulated); let text = self.format_result(&redacted_accumulated); let content = vec![ContentItem { @@ -2220,6 +2330,10 @@ impl ExecutionRouter { } } + fn changed_registration() -> StreamOutcome { + Self::stream_error("The tool registration changed during this call.".into()) + } + fn stream_error(text: String) -> StreamOutcome { ( vec![ContentItem { diff --git a/mcp/typescript/src/server/factory.ts b/mcp/typescript/src/server/factory.ts index 3ac333c0..b170fc8d 100644 --- a/mcp/typescript/src/server/factory.ts +++ b/mcp/typescript/src/server/factory.ts @@ -105,6 +105,12 @@ export interface MCPServerFactoryOptions { richDescription?: boolean; } +function outputSchemaForTool(descriptor: ModuleDescriptor): Tool["outputSchema"] { + return descriptor.outputSchema.type === "object" && !AsyncTaskBridge.isAsyncModuleDescriptor(descriptor) + ? descriptor.outputSchema as Tool["outputSchema"] + : undefined; +} + export class MCPServerFactory { private readonly _annotationMapper: AnnotationMapper; private readonly _richDescription: boolean; @@ -316,9 +322,8 @@ export class MCPServerFactory { }, }; - if (descriptor.outputSchema.type === "object" && !AsyncTaskBridge.isAsyncModuleDescriptor(descriptor)) { - tool.outputSchema = structuredClone(descriptor.outputSchema) as Tool["outputSchema"]; - } + const outputSchema = outputSchemaForTool(descriptor); + if (outputSchema !== undefined) tool.outputSchema = structuredClone(outputSchema); const hasStreaming = descriptor.annotations?.streaming === true; @@ -694,8 +699,12 @@ export class MCPServerFactory { const moduleId = this._toolSources.get(tool)?.moduleId ?? name; const toolArgs = (args ?? {}) as Record; + let responseTool = tool; // Build HandleCallExtra from MCP SDK extra const handleCallExtra: HandleCallExtra = { + onOutputDescriptor(descriptor) { + responseTool = { ...tool, outputSchema: outputSchemaForTool(descriptor) }; + }, signal: extra?.signal, sendNotification: extra?.sendNotification ? (notification: Record) => @@ -808,7 +817,7 @@ export class MCPServerFactory { } return supportsStructuredOutput(server, extra) - ? addStructuredOutput(result, tool) + ? addStructuredOutput(result, responseTool) : result; }); } diff --git a/mcp/typescript/src/server/router.ts b/mcp/typescript/src/server/router.ts index eb954b88..0e852b96 100644 --- a/mcp/typescript/src/server/router.ts +++ b/mcp/typescript/src/server/router.ts @@ -128,6 +128,8 @@ export interface HandleCallExtra { approvalResumeToken?: string; /** Per-request response handoff, created by the server factory. */ approvalReply?: ApprovalReplyCapture; + /** @internal Hand off the live Core schema only after a successful invocation. */ + onOutputDescriptor?: (descriptor: ModuleDescriptor) => void; /** MCP request cancellation, including transport disconnect. */ signal?: AbortSignal; sendNotification?: (notification: Record) => Promise; @@ -346,6 +348,7 @@ export class ExecutionRouter { private async _maybeRedact( toolName: string, result: unknown, + outputSchema = this._outputSchemaMap[toolName] ?? {}, ): Promise { if (!this._redactOutput || result == null) return result; try { @@ -355,7 +358,7 @@ export class ExecutionRouter { if (typeof redactSensitive !== "function") { throw new Error("Output redaction failed"); } - return redactSensitive(result, this._outputSchemaMap[toolName] ?? {}); + return redactSensitive(result, outputSchema); } catch { // Never expose the original result or the redactor's exception details. throw new Error("Output redaction failed"); @@ -715,9 +718,12 @@ export class ExecutionRouter { let versionHint: string | undefined = extra?.versionHint ?? extra?._meta?.apcore?.version; const coreExecutor = isCoreExecutor(this._executor); + const registry = this._executor.registry; + let descriptor: ModuleDescriptor | null = null; + let selectedModule: unknown; let declaredStreaming = false; try { - const descriptor = this._executor.registry?.getDefinition?.(toolName); + descriptor = registry?.getDefinition?.(toolName) ?? null; declaredStreaming = !coreExecutor && descriptor?.annotations?.streaming === true; if (!versionHint) { const metaHint = descriptor?.metadata?.versionHint; @@ -725,14 +731,24 @@ export class ExecutionRouter { versionHint = metaHint; } } - if (!declaredStreaming && typeof this._executor.streamWithCompletion === "function") { - const module = this._executor.registry?.get?.(toolName, versionHint); - declaredStreaming = module != null && isStreamingModule(module as Module); + if (coreExecutor || (!declaredStreaming && typeof this._executor.streamWithCompletion === "function")) { + selectedModule = registry?.get?.(toolName, versionHint); + declaredStreaming = selectedModule != null && isStreamingModule(selectedModule as Module); } } catch { // Registry lookup is best-effort for structurally compatible executors. } + const generation = coreExecutor ? registry.publicGeneration?.(toolName) : undefined; + const outputSchema = coreExecutor ? descriptor?.outputSchema ?? {} : undefined; + const protectOutput = (output: unknown): Promise => { + if (coreExecutor && (descriptor === null || selectedModule == null || + registry.get?.(toolName) !== selectedModule || registry.publicGeneration?.(toolName) !== generation)) { + throw new Error("Tool output registration could not be verified"); + } + return this._maybeRedact(toolName, output, outputSchema); + }; + // ── Streaming path ──────────────────────────────────────────────── const wantsProgress = progressToken !== undefined && sendNotification !== undefined; const customStreamRequested = wantsProgress && !coreExecutor; @@ -750,9 +766,11 @@ export class ExecutionRouter { if (chunks) { const progress = wantsProgress ? { token: progressToken, send: sendNotification } : undefined; const output = await runApprovalInvocation(extra?.approvalReply, context.data, () => - this._collectStream(toolName, chunks, execution, progress)); - const redacted = await this._maybeRedact(toolName, output); - return [[{ type: "text", text: await this._formatResult(redacted) }], false, effectiveTraceId]; + this._collectStream(chunks, execution, protectOutput, progress)); + const redacted = await protectOutput(output); + const text = await this._formatResult(redacted); + if (coreExecutor && descriptor !== null) extra?.onOutputDescriptor?.(descriptor); + return [[{ type: "text", text }], false, effectiveTraceId]; } // ── Non-streaming path ──────────────────────────────────────────── @@ -794,7 +812,7 @@ export class ExecutionRouter { callFn(toolName, executionArgs, context, versionHint)); } - const redacted = await this._maybeRedact(toolName, result); + const redacted = await protectOutput(result); const content: TextContentDict[] = [ { @@ -804,8 +822,8 @@ export class ExecutionRouter { } as TextContentDict, ]; - const traceId = effectiveTraceId; - return [content, false, traceId]; + if (coreExecutor && descriptor !== null) extra?.onOutputDescriptor?.(descriptor); + return [content, false, effectiveTraceId]; } catch (error: unknown) { // Error messages, stacks, codes and attached fields may contain secrets. console.error("Tool execution failed"); @@ -824,9 +842,9 @@ export class ExecutionRouter { } private async _collectStream( - toolName: string, chunks: AsyncIterable>, execution: StreamExecution | null, + protectOutput: (output: unknown) => Promise, progress?: { token: string | number; send: NonNullable }, ): Promise> { let accumulated: Record = {}; @@ -835,7 +853,7 @@ export class ExecutionRouter { for await (const chunk of chunks) { if (!execution) accumulated = deepMerge(accumulated, chunk); if (progress) { - const safeChunk = await this._maybeRedact(toolName, chunk); + const safeChunk = await protectOutput(chunk); await progress.send({ method: "notifications/progress", params: { progressToken: progress.token, progress: ++count, message: JSON.stringify(safeChunk) }, diff --git a/mcp/typescript/src/types.ts b/mcp/typescript/src/types.ts index ed4dcb0d..40226c07 100644 --- a/mcp/typescript/src/types.ts +++ b/mcp/typescript/src/types.ts @@ -118,6 +118,8 @@ export interface Registry { list(options?: { tags?: string[] | null; prefix?: string | null }): string[]; getDefinition(moduleId: string): ModuleDescriptor | null; get?(moduleId: string, versionHint?: string): unknown; + /** @internal Opaque generation of a public Core registration. */ + publicGeneration?(moduleId: string): object | null; has?(moduleId: string): boolean; on(event: string, callback: (...args: unknown[]) => void): void; discover?(): Promise; diff --git a/mcp/typescript/tests/server/capability-discovery.test.ts b/mcp/typescript/tests/server/capability-discovery.test.ts index 22ca04ab..fe15ede2 100644 --- a/mcp/typescript/tests/server/capability-discovery.test.ts +++ b/mcp/typescript/tests/server/capability-discovery.test.ts @@ -20,12 +20,19 @@ const inputSchema = { it("lists the authorized caller's tools and documentation from the live Core registration", async () => { const registry = new Registry(); - const execute = vi.fn(() => ({ ok: true })); - async function register(documentation: string, schema = inputSchema, version = "1.1.0"): Promise { + const execute = vi.fn<() => Record>(() => ({ ok: true })); + const originalOutput = { + type: "object", properties: { ok: { type: "boolean" } }, + required: ["ok"], additionalProperties: false, + }; + async function register( + documentation: string, schema = inputSchema, version = "1.1.0", + outputSchema: Record = originalOutput, + ): Promise { await registry.register(moduleId, { description: "A role-scoped module", inputSchema: schema, - outputSchema: { type: "object" }, + outputSchema, annotations: createAnnotations({ readonly: true }), execute, }, version, { documentation, display: { mcp: { alias } }, versionHint: "1.1.0" }); @@ -85,8 +92,21 @@ it("lists the authorized caller's tools and documentation from the live Core reg expect(await registry.safeUnregister(moduleId)).toBe(true); const replacement = { ...inputSchema, $defs: { message: { type: "string", minLength: 2 } } }; - await register("Replacement documentation", replacement); - expect((await client.listTools()).tools).toMatchObject([{ name: alias, inputSchema: replacement }]); + const liveOutput = { + type: "object", + properties: { + headline: { type: "string" }, + memo: { type: "string", "x-sensitive": true }, + comment: { type: "string", "x-sensitive": true }, + }, + required: ["headline", "memo"], + additionalProperties: false, + }; + execute.mockReturnValue({ headline: "reviewed", memo: "fixture-private-memo", comment: "fixture-private-comment" }); + await register("Replacement documentation", replacement, "1.1.0", liveOutput); + expect((await client.listTools()).tools).toMatchObject([ + { name: alias, inputSchema: replacement, outputSchema: liveOutput }, + ]); expect((await client.readResource({ uri: `docs://${moduleId}` })).contents) .toMatchObject([{ text: "Replacement documentation" }]); token = "fixture-observer"; @@ -96,7 +116,11 @@ it("lists the authorized caller's tools and documentation from the live Core reg expect(forbidden.isError).toBe(true); token = "fixture-reader"; const allowed = await client.callTool({ name: alias, arguments: { message: "hello" } }); - expect(allowed.structuredContent).toEqual({ ok: true }); + const redacted = { headline: "reviewed", memo: "***REDACTED***", comment: "***REDACTED***" }; + expect(allowed.isError).not.toBe(true); + expect(allowed.structuredContent).toEqual(redacted); + expect(allowed.content).toMatchObject([{ type: "text", text: JSON.stringify(redacted) }]); + expect(JSON.stringify(allowed)).not.toContain("fixture-private-"); expect(audit).toHaveBeenCalledTimes(2); expect(execute).toHaveBeenCalledTimes(1); From a6ac98c61f5ff44e9ae92e5056d218161f9d9e61 Mon Sep 17 00:00:00 2001 From: tercel Date: Sat, 28 Nov 2026 02:29:54 +0800 Subject: [PATCH 3/5] fix(mcp): share live output binding with typed Rust calls Signed-off-by: tercel --- mcp/rust/src/server/router.rs | 81 ++++++++++++++++++++++------------- 1 file changed, 51 insertions(+), 30 deletions(-) diff --git a/mcp/rust/src/server/router.rs b/mcp/rust/src/server/router.rs index 30762a7f..244e8bcc 100644 --- a/mcp/rust/src/server/router.rs +++ b/mcp/rust/src/server/router.rs @@ -455,7 +455,7 @@ struct LiveCallOutput { } tokio::task_local! { - static LIVE_CALL_OUTPUT: Arc; + static LIVE_CALL_OUTPUT: Option>; } pub(crate) enum WireOutputSchema { @@ -899,12 +899,21 @@ impl ExecutionRouter { fn current_call_output(&self, name: &str) -> bool { LIVE_CALL_OUTPUT .try_with(|binding| { - let (current, _) = self.executor.as_ref()?.discovery_executor(self.trace)?; - let registration = current.registry().get(name).ok().flatten()?; - let selected = binding.registration.as_ref()?; - Arc::ptr_eq(selected, ®istration).then_some(()) + let Some(binding) = binding else { + return true; + }; + let current = self + .executor + .as_ref() + .and_then(|executor| executor.discovery_executor(self.trace)) + .and_then(|(executor, _)| executor.registry().get(name).ok().flatten()); + binding + .registration + .as_ref() + .zip(current.as_ref()) + .is_some_and(|(selected, current)| Arc::ptr_eq(selected, current)) }) - .map_or(true, |matched| matched.is_some()) + .unwrap_or(true) } /// Redact sensitive fields from tool output before formatting. @@ -917,11 +926,13 @@ impl ExecutionRouter { if !self.redact_output { return result.clone(); } - if let Ok(redacted) = LIVE_CALL_OUTPUT.try_with(|output| { - output.schema.as_ref().map_or_else( - || result.clone(), - |schema| apcore::redact_sensitive(result, schema), - ) + if let Ok(Some(redacted)) = LIVE_CALL_OUTPUT.try_with(|output| { + output.as_ref().map(|output| { + output.schema.as_ref().map_or_else( + || result.clone(), + |schema| apcore::redact_sensitive(result, schema), + ) + }) }) { return redacted; } @@ -1090,23 +1101,29 @@ impl ExecutionRouter { arguments: &Value, extra: Option<&Value>, ) -> (StreamOutcome, WireOutputSchema) { - let Some(output) = self.live_call_output(tool_name).map(Arc::new) else { - return ( - self.dispatch_call(tool_name, arguments, extra).await, - WireOutputSchema::Configured, - ); - }; + self.with_call_output(tool_name, self.dispatch_call(tool_name, arguments, extra)) + .await + } + + async fn with_call_output( + &self, + tool_name: &str, + dispatch: impl Future, + ) -> (StreamOutcome, WireOutputSchema) { + let output = self.live_call_output(tool_name).map(Arc::new); let result = LIVE_CALL_OUTPUT - .scope(Arc::clone(&output), async { - let outcome = self.dispatch_call(tool_name, arguments, extra).await; + .scope(output.clone(), async { + let outcome = dispatch.await; if !outcome.1 && !self.current_call_output(tool_name) { return Self::changed_registration(); } outcome }) .await; - let schema = output.advertise.then(|| output.schema.clone()).flatten(); - (result, WireOutputSchema::Live(schema)) + let schema = output.map_or(WireOutputSchema::Configured, |output| { + WireOutputSchema::Live(output.schema.as_ref().filter(|_| output.advertise).cloned()) + }); + (result, schema) } async fn dispatch_call( @@ -1542,18 +1559,22 @@ impl ExecutionRouter { } } - self.dispatch_stream_or_call( + self.with_call_output( tool_name, - arguments, - &context_value, - None, - &apcore_ctx, - extra - .progress_token - .as_ref() - .zip(extra.send_notification.as_ref()), + self.dispatch_stream_or_call( + tool_name, + arguments, + &context_value, + None, + &apcore_ctx, + extra + .progress_token + .as_ref() + .zip(extra.send_notification.as_ref()), + ), ) .await + .0 } // ----------------------------------------------------------------------- From 43cd6c0d9cb5b182891963c874d37e967691f729 Mon Sep 17 00:00:00 2001 From: tercel Date: Sat, 28 Nov 2026 08:17:00 +0800 Subject: [PATCH 4/5] fix(mcp): align discovery and output with the executing registration Signed-off-by: tercel --- .github/workflows/python.yml | 2 +- .github/workflows/rust.yml | 4 +- .github/workflows/typescript.yml | 2 +- a2a/rust/Cargo.lock | 2 +- a2a/typescript/pnpm-lock.yaml | 2 +- cli/rust/Cargo.lock | 2 +- cli/typescript/pnpm-lock.yaml | 2 +- mcp/python/src/apcore_mcp/server/factory.py | 3 + mcp/python/src/apcore_mcp/server/router.py | 60 +++-- .../tests/server/test_capability_discovery.py | 92 ++++++- mcp/rust/Cargo.lock | 2 +- mcp/rust/src/apcore_mcp.rs | 233 +++++++++++++++++- mcp/rust/src/server/router.rs | 44 +++- mcp/typescript/pnpm-lock.yaml | 2 +- .../tests/server/capability-discovery.test.ts | 54 +++- toolkit/rust/Cargo.lock | 2 +- 16 files changed, 452 insertions(+), 56 deletions(-) diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 23ddd725..4ff90bad 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -15,7 +15,7 @@ permissions: contents: read env: - CORE_REF: de0c797760796daeefc1ba70d1e44263ea6519f1 + CORE_REF: 625aa3ecbd1d0343fe62ab18c0a9943c17495199 jobs: test: diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 8abb6089..d943f761 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -22,9 +22,9 @@ permissions: env: # The released lockfiles already reference these prereleases. Bootstrap CI # from the reviewed Core commit while those versions are unpublished. - CORE_REF: de0c797760796daeefc1ba70d1e44263ea6519f1 + CORE_REF: 625aa3ecbd1d0343fe62ab18c0a9943c17495199 CORE_CRATE_VERSION: 1.0.0-alpha.4 - CORE_CRATE_SHA256: 412082f3f58f5a59165f20e1df00f7191b5e382ea59f2369eb486f963cb7d604 + CORE_CRATE_SHA256: 7d5e08c5bbc5cddf5c72b121cbec90c1c551993dbee7c7cc88e30950941b63ad jobs: source: diff --git a/.github/workflows/typescript.yml b/.github/workflows/typescript.yml index e526cb48..1ee59bc9 100644 --- a/.github/workflows/typescript.yml +++ b/.github/workflows/typescript.yml @@ -15,7 +15,7 @@ permissions: contents: read env: - CORE_REF: de0c797760796daeefc1ba70d1e44263ea6519f1 + CORE_REF: 625aa3ecbd1d0343fe62ab18c0a9943c17495199 jobs: test: diff --git a/a2a/rust/Cargo.lock b/a2a/rust/Cargo.lock index 723973af..1f41a70a 100644 --- a/a2a/rust/Cargo.lock +++ b/a2a/rust/Cargo.lock @@ -94,7 +94,7 @@ dependencies = [ name = "apcore" version = "1.0.0-alpha.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "412082f3f58f5a59165f20e1df00f7191b5e382ea59f2369eb486f963cb7d604" +checksum = "7d5e08c5bbc5cddf5c72b121cbec90c1c551993dbee7c7cc88e30950941b63ad" dependencies = [ "async-stream", "async-trait", diff --git a/a2a/typescript/pnpm-lock.yaml b/a2a/typescript/pnpm-lock.yaml index 2c83beac..3705f2e1 100644 --- a/a2a/typescript/pnpm-lock.yaml +++ b/a2a/typescript/pnpm-lock.yaml @@ -657,7 +657,7 @@ packages: resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==} apcore-js@1.0.0-alpha.4: - resolution: {integrity: sha512-Ix49EPRQBVezM4mp59wGNW3AI7RFvD1I9iwPoYp/F81/gUZQIJ1CLjQkcFsiNME14EIGmcLL+noa/ttVg6qIcQ==} + resolution: {integrity: sha512-APFaeBqZ0u0BCmeDzGOJ05Byt16zY96NAlqUiRtIEDY51lzLNP4mfr6B6aicBvFZ1Lg4UQDmVKumpkxjXaOiyA==} engines: {node: '>=20.0.0'} peerDependencies: typescript: ^5.5.0 diff --git a/cli/rust/Cargo.lock b/cli/rust/Cargo.lock index 405eaf98..f6b12ffe 100644 --- a/cli/rust/Cargo.lock +++ b/cli/rust/Cargo.lock @@ -135,7 +135,7 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" name = "apcore" version = "1.0.0-alpha.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "412082f3f58f5a59165f20e1df00f7191b5e382ea59f2369eb486f963cb7d604" +checksum = "7d5e08c5bbc5cddf5c72b121cbec90c1c551993dbee7c7cc88e30950941b63ad" dependencies = [ "async-stream", "async-trait", diff --git a/cli/typescript/pnpm-lock.yaml b/cli/typescript/pnpm-lock.yaml index 55b96549..85240567 100644 --- a/cli/typescript/pnpm-lock.yaml +++ b/cli/typescript/pnpm-lock.yaml @@ -732,7 +732,7 @@ packages: resolution: {integrity: sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==} apcore-js@1.0.0-alpha.4: - resolution: {integrity: sha512-Ix49EPRQBVezM4mp59wGNW3AI7RFvD1I9iwPoYp/F81/gUZQIJ1CLjQkcFsiNME14EIGmcLL+noa/ttVg6qIcQ==} + resolution: {integrity: sha512-APFaeBqZ0u0BCmeDzGOJ05Byt16zY96NAlqUiRtIEDY51lzLNP4mfr6B6aicBvFZ1Lg4UQDmVKumpkxjXaOiyA==} engines: {node: '>=20.0.0'} peerDependencies: typescript: ^5.5.0 diff --git a/mcp/python/src/apcore_mcp/server/factory.py b/mcp/python/src/apcore_mcp/server/factory.py index f3668539..2ad6fc18 100644 --- a/mcp/python/src/apcore_mcp/server/factory.py +++ b/mcp/python/src/apcore_mcp/server/factory.py @@ -782,6 +782,9 @@ async def send_notification(notification: dict[str, Any]) -> None: else: text_contents.append(mcp_types.TextContent(type="text", text=item["text"])) output_schema = published.outputSchema if published is not None else None + if output_schema is not None and "_mcp_live_output_schema" in extra: + schema = extra["_mcp_live_output_schema"] + output_schema = schema if isinstance(schema, dict) and schema.get("type") == "object" else None return _build_call_result(text_contents, is_error, output_schema, approval=pending_approval) sdk_call_tool = server.request_handlers[mcp_types.CallToolRequest] diff --git a/mcp/python/src/apcore_mcp/server/router.py b/mcp/python/src/apcore_mcp/server/router.py index dd0c8ce3..e88df7ba 100644 --- a/mcp/python/src/apcore_mcp/server/router.py +++ b/mcp/python/src/apcore_mcp/server/router.py @@ -10,6 +10,7 @@ from collections import OrderedDict from collections.abc import Callable, Coroutine from contextlib import aclosing +from copy import deepcopy from typing import Any from apcore import APCore, CancelToken, Context, Executor, Identity, ModuleError, StreamingModule @@ -261,24 +262,31 @@ def _select_wire_version( def _output_projection( self, tool_name: str, version_hint: str | None - ) -> tuple[str | None, dict[str, Any] | None]: - if not self._redact_output or not self._core_backend: - return version_hint, None + ) -> tuple[str | None, dict[str, Any] | None, Callable[[], None] | None]: + if not self._core_backend: + return version_hint, None, None registry = self._executor.registry - definition = registry.get_definition(tool_name, version_hint) - if definition is None: - if version_hint is not None: - raise ModuleError("MODULE_NOT_FOUND", f"Module '{tool_name}' not found") - # Let Core report its ordinary lookup error without falling back - # to output metadata from a removed registration. - return None, {} - # Resolve redaction against the current registered schema, even if the - # default version string stayed fixed during a replacement. - if version_hint is not None and _matches_registered_version( + selected = registry._resolve_registration(tool_name, version_hint) + if selected is None and version_hint is not None: + raise ModuleError("MODULE_NOT_FOUND", f"Module '{tool_name}' not found") + definition = registry._describe_registration(tool_name, selected, warn_deprecation=False) if selected else None + if definition is not None and version_hint is not None and _matches_registered_version( registry, tool_name, version_hint, definition.version, ): version_hint = definition.version - return version_hint, definition.output_schema or {} + + def check_registration() -> None: + current = registry._resolve_registration(tool_name, version_hint) + if ( + selected is None + or current is None + or current.module is not selected.module + or current.metadata is not selected.metadata + ): + raise ModuleError("MODULE_EXECUTE_ERROR", "Tool registration changed during invocation") + + schema = deepcopy(definition.output_schema) if definition is not None else {} + return version_hint, schema or {}, check_registration def _format_result(self, result: Any) -> str: """Format an execution result into text for LLM consumption. @@ -682,7 +690,7 @@ async def _elicit_callback( if use_stream: return await self._handle_completed_stream( - tool_name, arguments, progress_token, send_notification, context, version_hint + tool_name, arguments, progress_token, send_notification, context, version_hint, wire_response=extra ) # Raw chunk executors predate the completion API. Keep the public @@ -699,7 +707,9 @@ async def _elicit_callback( ) # Non-streaming path - return await self._handle_call_async(tool_name, arguments, context=context, version_hint=version_hint) + return await self._handle_call_async( + tool_name, arguments, context=context, version_hint=version_hint, wire_response=extra, + ) def _resolve_identity(self, extra: dict[str, Any] | None) -> Any: """[A-D-211] Resolve identity with extras-then-ContextVar fallback. @@ -831,10 +841,12 @@ async def _handle_call_async( arguments: dict[str, Any], context: Any | None = None, version_hint: str | None = None, + *, + wire_response: dict[str, Any] | None = None, ) -> tuple[list[dict[str, Any]], bool, str | None]: """Non-streaming execution via executor.call_async().""" try: - version_hint, output_schema = self._output_projection(tool_name, version_hint) + version_hint, output_schema, check_registration = self._output_projection(tool_name, version_hint) call_kwargs = {"version_hint": version_hint} if version_hint is not None else {} call_args = (tool_name, arguments, context) if self._call_async_accepts_context else (tool_name, arguments) if self._trace and (version_hint is None or self._core_backend): @@ -855,6 +867,10 @@ async def _handle_call_async( else: result = await self._executor.call_async(*call_args, **call_kwargs) trace_dict = None + if check_registration is not None: + check_registration() + if wire_response is not None: + wire_response["_mcp_live_output_schema"] = output_schema result = self._maybe_redact(tool_name, result, output_schema) text_output = self._format_result(result) content: list[dict[str, Any]] = [{"type": "text", "text": text_output}] @@ -878,21 +894,29 @@ async def _handle_completed_stream( send_notification: Callable[[dict[str, Any]], Coroutine[Any, Any, None]] | None, context: Context, version_hint: str | None, + *, + wire_response: dict[str, Any] | None = None, ) -> tuple[list[dict[str, Any]], bool, str | None]: """Stream progress and take final output from the same execution.""" try: - version_hint, output_schema = self._output_projection(tool_name, version_hint) + version_hint, output_schema, check_registration = self._output_projection(tool_name, version_hint) kwargs = {"version_hint": version_hint} if version_hint is not None else {} async with aclosing(self._open_completed_stream(tool_name, arguments, context, **kwargs)) as execution: index = 0 async for chunk in execution.chunks: index += 1 if progress_token is not None and send_notification is not None: + if check_registration is not None: + check_registration() await self._send_chunk( tool_name, chunk, index, progress_token, send_notification, output_schema ) completion = await execution.completion() result = self._require_completed_output(completion) + if check_registration is not None: + check_registration() + if wire_response is not None: + wire_response["_mcp_live_output_schema"] = output_schema formatted = self._format_result(self._maybe_redact(tool_name, result, output_schema)) content: list[dict[str, Any]] = [{"type": "text", "text": formatted}] self._attach_traceparent(content, context) diff --git a/mcp/python/tests/server/test_capability_discovery.py b/mcp/python/tests/server/test_capability_discovery.py index d6640fb3..fe20bd85 100644 --- a/mcp/python/tests/server/test_capability_discovery.py +++ b/mcp/python/tests/server/test_capability_discovery.py @@ -2,10 +2,12 @@ from __future__ import annotations +import asyncio import json import httpx -from apcore import ACL, ACLRule, Executor, Identity, Registry +import pytest +from apcore import ACL, ACLRule, Executor, Identity, ModuleAnnotations, Registry from apcore_mcp import APCoreMCP from tests.server.test_scoped_approval_wire import _HttpSession @@ -128,3 +130,91 @@ async def test_discovery_reads_the_current_same_version_registration() -> None: assert not result.isError assert result.structuredContent is not None assert "private fixture output" not in result.model_dump_json() + + + +@pytest.mark.parametrize("streaming", [False, True]) +async def test_in_flight_replacement_withholds_unbound_output(streaming: bool) -> None: + class StreamingReport(Report): + annotations = ModuleAnnotations(streaming=True) + + async def stream(self, inputs, context): + yield await self.execute(inputs, context) + + entered = asyncio.Event() + resume = asyncio.Event() + + class PausedLookup: + async def before_step(self, name, state): + if name == "module_lookup": + entered.set() + await resume.wait() + + module_id = "fixture.report" + registry = Registry() + report_class = StreamingReport if streaming else Report + original = report_class() + registry.register(module_id, original, version="1.0.0") + executor = Executor(registry) + executor.current_strategy.add_step_middleware(PausedLookup()) + progress: list[str | None] = [] + + async def record_progress(_progress, _total, message): + progress.append(message) + + async with connected_client(executor, async_tasks=False) as session, asyncio.timeout(4): + call = asyncio.create_task(session.call_tool(module_id, {"count": 3}, progress_callback=record_progress)) + try: + await entered.wait() + registry.unregister(module_id) + replacement = report_class() + replacement.output_schema = { + "type": "object", + "properties": {"count": {"type": "integer", "x-sensitive": True}}, + } + registry.register(module_id, replacement, version="1.0.0") + finally: + resume.set() + result = await call + + assert original.calls == 0 and replacement.calls == 1 + assert result.isError + assert "registration changed" in result.content[0].text.lower() + assert result.structuredContent is None + assert progress == [] + + +async def test_http_discovery_filters_conditional_and_hidden_and_marks_definite_approval() -> None: + registry = Registry() + registry.register("demo.conditional", Report(), metadata={"documentation": "Conditional example."}) + + class Hidden(Report): + annotations = ModuleAnnotations(discoverable=False) + + class Approval(Report): + annotations = ModuleAnnotations(requires_approval=True) + + registry.register("demo.hidden", Hidden(), metadata={"documentation": "Hidden example."}) + registry.register("demo.approval", Approval()) + acl = ACL([ + ACLRule(callers=["@external"], targets=["demo.conditional"], effect="deny", conditions={ + "arguments": {"has_key": ["count"]}, + }), + ACLRule(callers=["@external"], targets=["demo.*"], effect="allow"), + ]) + + class Authenticator: + def authenticate(self, headers): + return Identity(id="viewer") if headers.get("authorization") == "Bearer viewer" else None + + mcp = APCoreMCP(Executor(registry, acl=acl), authenticator=Authenticator(), async_tasks=False) + async with mcp.async_serve() as app, httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://localhost", + ) as client: + session = _HttpSession(client, "Bearer viewer") + await session.initialize() + tools = (await session.request("tools/list", {}))["tools"] + assert [tool["name"] for tool in tools] == ["demo.approval"] + assert tools[0]["_meta"]["requiresApproval"] is True + resources = (await session.request("resources/list", {}))["resources"] + assert {resource["uri"] for resource in resources}.isdisjoint({"docs://demo.conditional", "docs://demo.hidden"}) diff --git a/mcp/rust/Cargo.lock b/mcp/rust/Cargo.lock index d013613b..33ba533e 100644 --- a/mcp/rust/Cargo.lock +++ b/mcp/rust/Cargo.lock @@ -100,7 +100,7 @@ dependencies = [ name = "apcore" version = "1.0.0-alpha.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "412082f3f58f5a59165f20e1df00f7191b5e382ea59f2369eb486f963cb7d604" +checksum = "7d5e08c5bbc5cddf5c72b121cbec90c1c551993dbee7c7cc88e30950941b63ad" dependencies = [ "async-stream", "async-trait", diff --git a/mcp/rust/src/apcore_mcp.rs b/mcp/rust/src/apcore_mcp.rs index 7f868495..239fb0b3 100644 --- a/mcp/rust/src/apcore_mcp.rs +++ b/mcp/rust/src/apcore_mcp.rs @@ -2694,7 +2694,10 @@ mod tests { } } - struct DiscoveryFixtureModule(String); + struct DiscoveryFixtureModule { + property: String, + annotations: ModuleAnnotations, + } #[async_trait::async_trait] impl Module for DiscoveryFixtureModule { @@ -2702,6 +2705,14 @@ mod tests { "Governed tool" } + fn annotations(&self) -> ModuleAnnotations { + self.annotations.clone() + } + + fn as_streaming(&self) -> Option<&dyn apcore::StreamingModule> { + self.annotations.streaming.then_some(self) + } + fn input_schema(&self) -> Value { json!({"type":"object"}) } @@ -2709,8 +2720,8 @@ mod tests { fn output_schema(&self) -> Value { json!({ "type": "object", - "properties": {(&self.0): {"type": "string", "x-sensitive": true}}, - "required": [&self.0], + "properties": {(&self.property): {"type": "string", "x-sensitive": true}}, + "required": [&self.property], "additionalProperties": false }) } @@ -2720,12 +2731,28 @@ mod tests { _: Value, _: &apcore::Context, ) -> Result { - Ok(json!({(&self.0): "local-redaction-fixture"})) + Ok(json!({(&self.property): "local-redaction-fixture"})) } } - fn register_discovery_fixture(registry: &Registry, id: &str, property: &str) { - let module = DiscoveryFixtureModule(property.to_owned()); + impl apcore::StreamingModule for DiscoveryFixtureModule { + fn stream_typed(&self, _: Value, _: &apcore::Context) -> apcore::ChunkStream { + Box::pin(futures::stream::iter([Ok( + json!({(&self.property): "local-redaction-fixture"}), + )])) + } + } + + fn register_discovery_fixture( + registry: &Registry, + id: &str, + property: &str, + annotations: ModuleAnnotations, + ) { + let module = DiscoveryFixtureModule { + property: property.to_owned(), + annotations, + }; let descriptor = ModuleDescriptor { module_id: id.into(), name: None, @@ -2739,7 +2766,7 @@ mod tests { output_schema: module.output_schema(), version: "1.0.0".into(), tags: vec![], - annotations: Some(ModuleAnnotations::default()), + annotations: Some(module.annotations()), examples: vec![], metadata: std::collections::HashMap::new(), display: None, @@ -2781,7 +2808,42 @@ mod tests { #[tokio::test] async fn test_http_discovery_filters_tools_and_resources_for_each_identity() { let registry = Arc::new(Registry::new()); - register_discovery_fixture(®istry, "demo.governed", "stale"); + register_discovery_fixture( + ®istry, + "demo.governed", + "stale", + ModuleAnnotations::default(), + ); + register_discovery_fixture( + ®istry, + "demo.conditional", + "mode", + ModuleAnnotations::default(), + ); + register_discovery_fixture( + ®istry, + "demo.hidden", + "secret", + ModuleAnnotations { + discoverable: false, + ..Default::default() + }, + ); + register_discovery_fixture( + ®istry, + "demo.requires_approval", + "mode", + ModuleAnnotations { + requires_approval: true, + ..Default::default() + }, + ); + let mut conditional_deny = apcore::ACLRule::new( + vec!["@external".into()], + vec!["demo.conditional".into()], + "deny", + ); + conditional_deny.conditions = Some(json!({"arguments":{"has_key":["mode"]}})); let mut rule = apcore::ACLRule::new( vec!["@external".into()], vec!["demo.*".into(), "system.manifest.search".into()], @@ -2789,7 +2851,7 @@ mod tests { ); rule.conditions = Some(json!({"roles":["reader"]})); let mut executor = Executor::new(Arc::clone(®istry), Config::default()); - executor.set_acl(apcore::ACL::new(vec![rule], "deny", None)); + executor.set_acl(apcore::ACL::new(vec![conditional_deny, rule], "deny", None)); let mut sys_config = Config::default(); sys_config.set("sys_modules.enabled", json!(true)); apcore::register_sys_modules(Arc::clone(®istry), &executor, &sys_config, None).unwrap(); @@ -2820,6 +2882,16 @@ mod tests { assert!(tools.iter().any(|tool| tool["name"] .as_str() .is_some_and(|name| name.starts_with("__apcore_task_")))); + assert!(!tools.iter().any(|tool| { + tool["name"] == "demo.conditional" || tool["name"] == "demo.hidden" + })); + let approval_tool = tools + .iter() + .find(|tool| tool["name"] == "demo.requires_approval"); + assert_eq!(approval_tool.is_some(), role == "reader"); + if let Some(tool) = approval_tool { + assert_eq!(tool["_meta"]["requiresApproval"], true); + } let resources = discovery_http_request(&app, role, "resources/list", json!({})).await; assert_eq!( resources["result"]["resources"] @@ -2837,6 +2909,16 @@ mod tests { ) .await; assert_eq!(doc.get("result").is_some(), role == "reader"); + for uri in ["docs://demo.conditional", "docs://demo.hidden"] { + assert!(!resources["result"]["resources"] + .as_array() + .unwrap() + .iter() + .any(|resource| resource["uri"] == uri)); + let rejected = + discovery_http_request(&app, role, "resources/read", json!({"uri":uri})).await; + assert!(rejected.get("error").is_some()); + } let called = discovery_http_request( &app, role, @@ -2864,13 +2946,34 @@ mod tests { searched["result"]["content"][0]["text"].as_str().unwrap(), ) .unwrap(); + assert_eq!(page["items"].as_array().unwrap().len(), 2); assert_eq!(page["items"][0]["module_id"], "demo.governed"); + assert_eq!(page["items"][1]["module_id"], "demo.requires_approval"); + assert_eq!(page["items"][1]["access_hint"], "requires_approval"); assert_eq!(page["next_cursor"], Value::Null); + let approval = discovery_http_request( + &app, + role, + "tools/call", + json!({"name":"demo.requires_approval","arguments":{}}), + ) + .await; + assert_eq!(approval["result"]["isError"], true); } } assert!(registry.unregister("demo.governed").unwrap()); - register_discovery_fixture(®istry, "demo.governed", "fresh"); - register_discovery_fixture(®istry, "demo.unpublished", "new"); + register_discovery_fixture( + ®istry, + "demo.governed", + "fresh", + ModuleAnnotations::default(), + ); + register_discovery_fixture( + ®istry, + "demo.unpublished", + "new", + ModuleAnnotations::default(), + ); let listing = discovery_http_request(&app, "reader", "tools/list", json!({})).await; let tools = listing["result"]["tools"].as_array().unwrap(); assert!(!tools.iter().any(|tool| tool["name"] == "demo.unpublished")); @@ -2927,6 +3030,114 @@ mod tests { ); } + #[tokio::test] + async fn test_http_discovery_uses_stream_and_background_strategies_when_tracing() { + verify_traced_discovery(true).await; + verify_traced_discovery(false).await; + } + + async fn verify_traced_discovery(default_allows_stream: bool) { + let registry = Arc::new(Registry::new()); + register_discovery_fixture( + ®istry, + "demo.streaming", + "label", + ModuleAnnotations { + streaming: true, + ..Default::default() + }, + ); + register_discovery_fixture( + ®istry, + "demo.unary", + "label", + ModuleAnnotations::default(), + ); + register_discovery_fixture( + ®istry, + "demo.background", + "label", + ModuleAnnotations { + extra: std::collections::HashMap::from([("mcp_async".into(), json!(true))]), + ..Default::default() + }, + ); + let mut rule = + apcore::ACLRule::new(vec!["@external".into()], vec!["demo.*".into()], "allow"); + rule.conditions = Some(json!({"roles":["reader"], "$not":{"max_call_depth":0}})); + let default_strategy = if default_allows_stream { + apcore::builtin_steps::build_standard_strategy() + } else { + apcore::pipeline_config::build_strategy_from_config(&json!({ + "configure": {"context_creation": {"match_modules": ["demo.unary"]}} + })) + .unwrap() + }; + let trace_override = if default_allows_stream { + "internal" + } else { + "standard" + }; + let mut executor = Executor::with_strategy(registry, Config::default(), default_strategy); + executor.set_acl(apcore::ACL::new(vec![rule], "deny", None)); + let mcp = APCoreMCP::builder() + .backend(BackendSource::Executor(Arc::new(executor))) + .strategy(trace_override) + .trace(true) + .build() + .unwrap(); + let (server, _, _, options, _, _) = mcp.build_server_components().unwrap(); + let handler = ServerHandler::from_server(&server, options).unwrap(); + let app = Arc::new(TransportManager::new(None)) + .build_streamable_http_app(Arc::new(handler), None) + .layer(crate::auth::middleware::AuthMiddlewareLayer::new(Arc::new( + DiscoveryFixtureAuth, + ))); + + let initialized = discovery_http_request( + &app, "reader", "initialize", + json!({"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"fixture","version":"1"}}), + ).await; + assert!(initialized.get("result").is_some()); + let stream = discovery_http_request( + &app, + "reader", + "tools/call", + json!({"name":"demo.streaming","arguments":{}}), + ) + .await; + assert_eq!( + stream["result"]["isError"], !default_allows_stream, + "{stream}", + ); + let background = discovery_http_request( + &app, + "reader", + "tools/call", + json!({"name":"demo.background","arguments":{}}), + ) + .await; + assert_eq!(background["result"]["isError"], false, "{background}"); + let task: Value = + serde_json::from_str(background["result"]["content"][0]["text"].as_str().unwrap()) + .unwrap(); + assert!(task["task_id"].is_string()); + + let listing = discovery_http_request(&app, "reader", "tools/list", json!({})).await; + let tools = listing["result"]["tools"].as_array().unwrap(); + for name in ["demo.streaming", "demo.background"] { + assert_eq!( + tools.iter().any(|tool| tool["name"] == name), + default_allows_stream, + "{name}", + ); + } + assert_eq!( + tools.iter().any(|tool| tool["name"] == "demo.unary"), + !default_allows_stream, + ); + } + #[tokio::test] async fn test_governed_mcp_redacts_referenced_sensitive_output() { for draft_seven in [false, true] { diff --git a/mcp/rust/src/server/router.rs b/mcp/rust/src/server/router.rs index 244e8bcc..db3f196a 100644 --- a/mcp/rust/src/server/router.rs +++ b/mcp/rust/src/server/router.rs @@ -427,18 +427,45 @@ pub struct ContentItem { pub(crate) struct CoreDiscovery<'a> { executor: &'a apcore::Executor, - strategy: &'a apcore::ExecutionStrategy, + unary_strategy: &'a apcore::ExecutionStrategy, + has_async_bridge: bool, context: apcore::Context, } impl CoreDiscovery<'_> { pub(crate) fn descriptor(&self, module_id: &str) -> Option { - self.executor.get_callable_descriptor_for_strategy( - module_id, - None, - Some(&self.context), - self.strategy, - ) + let default_strategy = self.executor.strategy(); + let project = |strategy| { + self.executor.get_callable_descriptor_for_strategy( + module_id, + None, + Some(&self.context), + strategy, + ) + }; + if std::ptr::eq(default_strategy, self.unary_strategy) { + return project(default_strategy); + } + + let registry = self.executor.registry(); + let module = registry.get(module_id).ok()??; + // Core native streams and the async-task bridge both use the default + // pipeline. Only the unary call can take the traced override. + let descriptor = if module.as_streaming().is_some() { + project(default_strategy) + } else if self.has_async_bridge { + project(default_strategy) + .filter(AsyncTaskBridge::is_async_module_descriptor) + .or_else(|| { + project(self.unary_strategy).filter(|descriptor| { + !AsyncTaskBridge::is_async_module_descriptor(descriptor) + }) + }) + } else { + project(self.unary_strategy) + }?; + let current = registry.get(module_id).ok()??; + Arc::ptr_eq(&module, ¤t).then_some(descriptor) } pub(crate) fn documentation(&self, module_id: &str) -> Option { @@ -553,7 +580,8 @@ impl ExecutionRouter { .map_or_else(apcore::Context::anonymous, apcore::Context::new); Some(CoreDiscovery { executor, - strategy, + unary_strategy: strategy, + has_async_bridge: self.async_bridge.is_some(), context, }) } diff --git a/mcp/typescript/pnpm-lock.yaml b/mcp/typescript/pnpm-lock.yaml index afb3c6f3..e60a3b7e 100644 --- a/mcp/typescript/pnpm-lock.yaml +++ b/mcp/typescript/pnpm-lock.yaml @@ -620,7 +620,7 @@ packages: engines: {node: '>=8'} apcore-js@1.0.0-alpha.4: - resolution: {integrity: sha512-Ix49EPRQBVezM4mp59wGNW3AI7RFvD1I9iwPoYp/F81/gUZQIJ1CLjQkcFsiNME14EIGmcLL+noa/ttVg6qIcQ==} + resolution: {integrity: sha512-APFaeBqZ0u0BCmeDzGOJ05Byt16zY96NAlqUiRtIEDY51lzLNP4mfr6B6aicBvFZ1Lg4UQDmVKumpkxjXaOiyA==} engines: {node: '>=20.0.0'} peerDependencies: typescript: ^5.5.0 diff --git a/mcp/typescript/tests/server/capability-discovery.test.ts b/mcp/typescript/tests/server/capability-discovery.test.ts index fe15ede2..d4529be7 100644 --- a/mcp/typescript/tests/server/capability-discovery.test.ts +++ b/mcp/typescript/tests/server/capability-discovery.test.ts @@ -10,6 +10,9 @@ import { asyncServe } from "../../src/index.js"; const moduleId = "example.limited"; const alias = "reader_example"; +const argumentDependentId = "example.argument_dependent"; +const approvalId = "example.review"; +const hiddenId = "example.hidden"; const inputSchema = { type: "object", properties: { message: { $ref: "#/$defs/message" } }, @@ -17,6 +20,12 @@ const inputSchema = { $defs: { message: { type: "string" } }, additionalProperties: false, }; +const approvalInputSchema = { + type: "object", + properties: { message: { type: "string" } }, + required: ["message"], + additionalProperties: false, +}; it("lists the authorized caller's tools and documentation from the live Core registration", async () => { const registry = new Registry(); @@ -38,19 +47,38 @@ it("lists the authorized caller's tools and documentation from the live Core reg }, version, { documentation, display: { mcp: { alias } }, versionHint: "1.1.0" }); } await register("Initial documentation"); - await registry.register("example.hidden", { + await registry.register(hiddenId, { description: "Not discoverable", inputSchema, outputSchema: { type: "object" }, annotations: createAnnotations({ discoverable: false }), execute, }, "1.0.0", { documentation: "Hidden documentation" }); + await registry.register(argumentDependentId, { + description: "A module with an argument-dependent denial", + inputSchema, + outputSchema: originalOutput, + execute, + }, "1.0.0", { documentation: "Argument-dependent documentation" }); + await registry.register(approvalId, { + description: "A module requiring approval", + inputSchema: approvalInputSchema, + outputSchema: originalOutput, + annotations: createAnnotations({ requiresApproval: true }), + execute, + }); const audit = vi.fn(); - const acl = new ACL([{ - callers: ["@external"], targets: ["example.*"], description: "", effect: "allow", - conditions: { roles: ["reader"] }, - }], "deny", audit); + const acl = new ACL([ + { + callers: ["@external"], targets: [argumentDependentId], description: "", effect: "deny", + conditions: { arguments: { has_key: ["message"] } }, + }, + { + callers: ["@external"], targets: ["example.*"], description: "", effect: "allow", + conditions: { roles: ["reader"] }, + }, + ], "deny", audit); const executor = new Executor({ registry, acl }); const reader = createIdentity("reader", "user", ["reader"]); const observer = createIdentity("observer", "user", ["observer"]); @@ -83,10 +111,14 @@ it("lists the authorized caller's tools and documentation from the live Core reg expect((await client.listResources()).resources).toEqual([]); await expect(client.readResource({ uri: `docs://${moduleId}` })).rejects.toThrow(/resource not found/i); token = "fixture-reader"; - expect((await client.listTools()).tools).toMatchObject([{ name: alias, inputSchema }]); + const approvalTool = { name: approvalId, inputSchema: approvalInputSchema, _meta: { requiresApproval: true } }; + expect((await client.listTools()).tools).toMatchObject([{ name: alias, inputSchema }, approvalTool]); expect((await client.listResources()).resources).toMatchObject([{ uri: `docs://${moduleId}` }]); expect((await client.readResource({ uri: `docs://${moduleId}` })).contents) .toMatchObject([{ text: "Initial documentation" }]); + for (const id of [argumentDependentId, hiddenId]) { + await expect(client.readResource({ uri: `docs://${id}` })).rejects.toThrow(/resource not found/i); + } expect(audit).not.toHaveBeenCalled(); expect(execute).not.toHaveBeenCalled(); @@ -106,6 +138,7 @@ it("lists the authorized caller's tools and documentation from the live Core reg await register("Replacement documentation", replacement, "1.1.0", liveOutput); expect((await client.listTools()).tools).toMatchObject([ { name: alias, inputSchema: replacement, outputSchema: liveOutput }, + approvalTool, ]); expect((await client.readResource({ uri: `docs://${moduleId}` })).contents) .toMatchObject([{ text: "Replacement documentation" }]); @@ -124,9 +157,16 @@ it("lists the authorized caller's tools and documentation from the live Core reg expect(audit).toHaveBeenCalledTimes(2); expect(execute).toHaveBeenCalledTimes(1); + const needsApproval = await client.callTool({ name: approvalId, arguments: { message: "hello" } }); + expect(needsApproval.isError).toBe(true); + expect(needsApproval.content).toMatchObject([{ type: "text", text: expect.stringMatching(/approval/i) }]); + const conditional = await client.callTool({ name: argumentDependentId, arguments: { message: "hello" } }); + expect(conditional.isError).toBe(true); + expect(execute).toHaveBeenCalledTimes(1); + expect(await registry.safeUnregister(moduleId)).toBe(true); await register("Different registered version", replacement, "2.0.0"); - expect((await client.listTools()).tools).toEqual([]); + expect((await client.listTools()).tools).toMatchObject([approvalTool]); } finally { await client.close(); await app.close(); diff --git a/toolkit/rust/Cargo.lock b/toolkit/rust/Cargo.lock index 1089111d..85f493cb 100644 --- a/toolkit/rust/Cargo.lock +++ b/toolkit/rust/Cargo.lock @@ -50,7 +50,7 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" name = "apcore" version = "1.0.0-alpha.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "412082f3f58f5a59165f20e1df00f7191b5e382ea59f2369eb486f963cb7d604" +checksum = "7d5e08c5bbc5cddf5c72b121cbec90c1c551993dbee7c7cc88e30950941b63ad" dependencies = [ "async-stream", "async-trait", From 56213ecfee9ebea9d5ad05376ed83b90b7e75399 Mon Sep 17 00:00:00 2001 From: tercel Date: Sat, 28 Nov 2026 08:29:54 +0800 Subject: [PATCH 5/5] fix(mcp): box Rust dispatch before task-local wrappers Signed-off-by: tercel --- mcp/rust/src/server/router.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/mcp/rust/src/server/router.rs b/mcp/rust/src/server/router.rs index db3f196a..4cae2e7c 100644 --- a/mcp/rust/src/server/router.rs +++ b/mcp/rust/src/server/router.rs @@ -1129,14 +1129,16 @@ impl ExecutionRouter { arguments: &Value, extra: Option<&Value>, ) -> (StreamOutcome, WireOutputSchema) { - self.with_call_output(tool_name, self.dispatch_call(tool_name, arguments, extra)) - .await + let dispatch = Box::pin(self.dispatch_call(tool_name, arguments, extra)); + self.with_call_output(tool_name, dispatch).await } + // Keep the dispatch state on the heap before task-local wrappers capture it. + // Inline propagation exhausts the default Windows main stack in debug builds. async fn with_call_output( &self, tool_name: &str, - dispatch: impl Future, + dispatch: Pin>>, ) -> (StreamOutcome, WireOutputSchema) { let output = self.live_call_output(tool_name).map(Arc::new); let result = LIVE_CALL_OUTPUT @@ -1587,8 +1589,7 @@ impl ExecutionRouter { } } - self.with_call_output( - tool_name, + let dispatch = Box::pin( self.dispatch_stream_or_call( tool_name, arguments, @@ -1600,9 +1601,8 @@ impl ExecutionRouter { .as_ref() .zip(extra.send_notification.as_ref()), ), - ) - .await - .0 + ); + self.with_call_output(tool_name, dispatch).await.0 } // -----------------------------------------------------------------------