diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 6c551330..b998e882 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -6,6 +6,7 @@ on: paths: &python-paths - '*/python/**' - '*/conformance/**' + - 'mcp/examples/management-reference/**' - '.github/workflows/python.yml' pull_request: paths: *python-paths @@ -73,6 +74,21 @@ jobs: PY - run: ruff check src/ tests/ - run: python -m pytest + - name: Verify the MCP management reference with both SDK versions + if: matrix.component == 'mcp' + working-directory: . + shell: bash + run: | + example=mcp/examples/management-reference + reference="$RUNNER_TEMP/mcp-management-reference" + legacy="$RUNNER_TEMP/mcp-management-legacy" + python -m venv "$reference" + python -m venv "$legacy" + "$reference/bin/python" -m pip install -r "$example/requirements-test.txt" "$RUNNER_TEMP"/core-wheel/apcore-*.whl + "$reference/bin/python" -m pip check + "$reference/bin/python" -m pytest -q "$example" + "$legacy/bin/python" -m pip install 'mcp==1.30.0' + "$legacy/bin/python" "$example/legacy_smoke.py" "$reference/bin/python" package: name: Python distribution (${{ matrix.component }}) diff --git a/mcp/docs/features/mcp-server-factory.md b/mcp/docs/features/mcp-server-factory.md index 56baeb07..ae978b6a 100644 --- a/mcp/docs/features/mcp-server-factory.md +++ b/mcp/docs/features/mcp-server-factory.md @@ -271,16 +271,17 @@ deployment choice. |---|---|---| | `system.health.summary` | resource | `apcore://system.health.summary` | | `system.health.module` | resource template | `apcore://system.health.module/{module_id}` | -| `system.usage.summary` | resource | `apcore://system.usage.summary{?period}` | +| `system.usage.summary` | resource | `apcore://system.usage.summary` | | `system.usage.module` | resource template | `apcore://system.usage.module/{module_id}{?period}` | | `system.manifest.full` | resource | `apcore://system.manifest.full` | | `system.manifest.module` | resource template | `apcore://system.manifest.module/{module_id}` | +| `system.manifest.search` | read-only tool | `system.manifest.search` | | `system.control.update_config` | tool | `system.control.update_config` | | `system.control.reload_module` | tool | `system.control.reload_module` | | `system.control.toggle_feature` | tool | `system.control.toggle_feature` | -The three `system.control.*` modules have side effects — that is what a tool is — and stay tools with -the approval bridge wired on the tool-call path exactly as before. The six read-only modules are +The three `system.control.*` tools use the approval bridge on the tool-call path. +`system.manifest.search` is a read-only tool that accepts search criteria. The six resource modules are excluded from `build_tools()`'s output and are instead served by the resource-handler registration step (below), whichever `module_id` prefix filter or resource-handler-only variant of that step the SDK exposes. @@ -296,7 +297,7 @@ uses for tool calls. This classification is also the reachability signal the [System Management Extension](./system-management-extension.md) (`com.aiperceivable/management`, aiperceivable/apcore-mcp#16 Phase A) advertises in `capabilities.extensions` — see that document for -the negotiation shape. Declaring or omitting that extension has no effect on whether any of the nine +the negotiation shape. Declaring or omitting that extension has no effect on whether any of the ten modules above are reachable; see its Design Constraint section. ### Unprotected control surface warning diff --git a/mcp/docs/features/overview.md b/mcp/docs/features/overview.md index 9222cc63..89464866 100644 --- a/mcp/docs/features/overview.md +++ b/mcp/docs/features/overview.md @@ -26,7 +26,7 @@ description: "Auto-generated index of all apcore-mcp feature specs with dependen | [Async Task Bridge](./async-task-bridge.md) | Routes async-hinted modules to apcore's AsyncTaskManager and exposes task meta-tools. | execution-router, error-mapper | released-v0.14.0 | | [Explorer UI](./explorer-ui.md) | Web dashboard for inspecting and testing tools. | mcp-server-factory, execution-router | released-v0.14.0 | | [Markdown](./markdown.md) | Renders `Tool.description` and OpenAI `function.description` as canonical apcore-toolkit Markdown for richer LLM tool-selection signal (`rich_description` / `richDescription` / `with_rich_description`). | apcore-toolkit 0.6+ (optional) | released-v0.15.0 | -| [System Management Extension](./system-management-extension.md) | Unofficial MCP extension (`com.aiperceivable/management`) advertising the `system.*` management surface's shape in `initialize`; Phase A only. | mcp-server-factory | released-v0.19.0 (Phase A) | +| [System Management Extension](./system-management-extension.md) | Unofficial MCP extension (`com.aiperceivable/management`) advertising the `system.*` management surface in `initialize`, with an SDK reference for `server/discover` and legacy compatibility. | mcp-server-factory | released-v0.19.0 (Phase A) | | [ACL Builder](./acl-builder.md) | Builds an `apcore.ACL` from the `mcp.acl` Config Bus section; owns the Config-Bus-shaped validation, wraps apcore's §6.2.1 pattern-array rejections with a rule index, and reports tier-2 never-matches findings at startup. | apcore 0.30.0 | released-v0.20.0 | | [OpenAPI Backend](./openapi-backend.md) | Third backend source — turns an OpenAPI 3.0/3.1 document into MCP tools via apcore-toolkit's `OpenAPIScanner` + `HTTPProxyRegistryWriter`. | apcore-toolkit 0.13.0, schema-converter, annotation-mapper, mcp-server-factory | released-v0.20.0 | diff --git a/mcp/docs/features/system-management-extension.md b/mcp/docs/features/system-management-extension.md index 78b9c763..75905bb3 100644 --- a/mcp/docs/features/system-management-extension.md +++ b/mcp/docs/features/system-management-extension.md @@ -1,12 +1,13 @@ --- -description: "com.aiperceivable/management MCP extension (Phase A, unofficial): identifier, capabilities.extensions negotiation shape, resource/tool conventions for the nine canonical system.* modules, ACL/approval interaction, degradation behavior." +description: "com.aiperceivable/management MCP extension (Phase A, unofficial): identifier, capabilities.extensions negotiation shape, resource/tool conventions, ACL/approval interaction, and the official SDK reference for #113." --- # System Management Extension (`com.aiperceivable/management`) > Feature spec for code-forge implementation planning. -> Tracking issue: aiperceivable/apcore-mcp#16 (Phase A only — B and C are separate follow-ups). -> Blocked by / depends on: [`system.* module projection`](./mcp-server-factory.md#system-module-projection-resources-vs-tools) (aiperceivable/apcore-mcp#15). +> Phase A: [#110](https://github.com/aiperceivable/apcore-surfaces/issues/110). +> Phases B and C: [#113](https://github.com/aiperceivable/apcore-surfaces/issues/113). +> Depends on: [`system.* module projection`](./mcp-server-factory.md#system-module-projection-resources-vs-tools) (aiperceivable/apcore-mcp#15). > Status: Phase A — unofficial extension. Not submitted to `modelcontextprotocol/modelcontextprotocol`. > Created: 2026-09-01 @@ -16,14 +17,14 @@ interpreted as described in RFC 2119. ## Purpose Publish the `system.*` management surface (health, usage, manifest, control) as a discoverable, -versioned MCP extension so a client can learn — from one field of the `initialize` handshake — that a -server exposes a known-shaped governance surface, instead of inferring it by pattern-matching -`module_id` strings. +versioned MCP extension. Clients that recognize the identifier can learn the server's management +conventions from the capability settings. This is [SEP-2133](https://modelcontextprotocol.io/seps/2133-extensions) **Phase A**: an *unofficial* extension, which SEP-2133 states "may be introduced and governed by developers outside the MCP -organization" with no approval required. Phase B (Working Group discussion) and Phase C (formal SEP -submission) are tracked separately and are out of scope for this document. +organization." Phase A is implemented in Python, TypeScript, and Rust. The +[reference implementation for #113](#reference-implementation-for-113) validates the same contract +across two MCP protocol revisions. ## Identifier @@ -31,10 +32,8 @@ submission) are tracked separately and are out of scope for this document. Format is `{vendor-prefix}/{extension-name}` per SEP-2133, where the vendor prefix is a reversed domain the author controls. `aiperceivable.com` is the project domain, and every project in the -ecosystem documents under `.aiperceivable.com`. SEP-2133 requires a *new* identifier for any -breaking change to this extension's shape, so this prefix and name **MUST** be treated as stable from -first publication — a future breaking revision ships under a new identifier, never a version bump of -this one. +ecosystem documents under `.aiperceivable.com`. The Phase A identifier **MUST** remain stable. A breaking revision to this Phase A contract uses a +new identifier. ## Design constraint — the extension is metadata, not a gate @@ -44,7 +43,7 @@ An adapter **MUST NOT** let declaring or omitting this extension change what a c lose access to anything: every `system.*` resource and tool **MUST** remain reachable through ordinary `resources/list` / `resources/read` / `tools/list` / `tools/call`, subject only to Activation (§6.6.3 layer 1), ACL (layer 2) and Approval (layer 3) as defined by - [PROTOCOL_SPEC §6.6.3](https://github.com/aiperceivable/apcore/blob/main/PROTOCOL_SPEC.md). + [PROTOCOL_SPEC §6.6.3](https://github.com/aiperceivable/apcore/blob/main/docs/spec/protocol-spec.md#663-defense-in-depth-model). - An adapter **MUST NOT** introduce a permission switch keyed off whether the *caller* declared this extension. PROTOCOL_SPEC §6.6.3 prohibits adapters from inventing permission mechanisms beyond Activation / ACL / Approval; a capability-gated access difference would be exactly that — a shadow @@ -54,13 +53,13 @@ An adapter **MUST NOT** let declaring or omitting this extension change what a c ## Negotiation -Advertised in the `initialize` response's `capabilities.extensions` map, keyed by identifier: +The Phase A adapters advertise the extension in the legacy `initialize` response. The reference +implementation also advertises it in `server/discover` on MCP 2026-07-28. Both responses use the +same `capabilities.extensions` entry. ```json { "capabilities": { - "tools": { "listChanged": true }, - "resources": { "listChanged": true }, "extensions": { "com.aiperceivable/management": { "surfaces": ["health", "usage", "manifest", "control"], @@ -73,15 +72,15 @@ Advertised in the `initialize` response's `capabilities.extensions` map, keyed b ### `surfaces` -An array drawn from the four-element set `["health", "usage", "manifest", "control"]`, reflecting only -what is **actually reachable** on this server instance: +An ordered array of registered groups drawn from `["health", "usage", "manifest", "control"]`. +Per-invocation access depends on Core governance. | Element | Present iff | |---|---| | `"health"` | `system.health.summary` or `system.health.module` is registered (`sys_modules.enabled = true`) | | `"usage"` | `system.usage.summary` or `system.usage.module` is registered | -| `"manifest"` | `system.manifest.full` or `system.manifest.module` is registered | -| `"control"` | any `system.control.*` module is registered (`sys_modules.enabled = true` **and** `sys_modules.events.enabled = true`) | +| `"manifest"` | `system.manifest.full`, `system.manifest.module`, or `system.manifest.search` is registered | +| `"control"` | a `system.control.*` module is registered (requires management, events, and control to be enabled) | An adapter **MUST NOT** advertise the extension at all — the whole `"com.aiperceivable/management"` key **MUST** be absent from `capabilities.extensions` — when `surfaces` would be empty (i.e. @@ -95,12 +94,12 @@ their disjunction and is not fine-grained enough on its own to populate `surface ### `protocolVersion` -The [PROTOCOL_SPEC](https://github.com/aiperceivable/apcore/blob/main/PROTOCOL_SPEC.md) version this -adapter's `system.*` projection was written against (currently `1.30.0`). A client MAY use this to -decide whether it understands the resource-URI and tool-annotation conventions below; an adapter -**MUST** update this string when it adopts a newer PROTOCOL_SPEC's `§6.6` changes. +The [PROTOCOL_SPEC](https://github.com/aiperceivable/apcore/blob/main/docs/spec/protocol-spec.md) version this +adapter's `system.*` projection targets. Phase A and the reference use the shared fixture value +`1.30.0`. A client MAY use it to interpret the resource URI and tool annotation conventions. +This setting is independent of the MCP connection revision and the installed Core package version. -## Resource and tool conventions for the nine canonical modules +## Resource and tool conventions for the ten canonical modules This section restates, for the extension's own reference-implementation contract, the classification [`system.* module projection`](./mcp-server-factory.md#system-module-projection-resources-vs-tools) @@ -111,14 +110,18 @@ shapes without probing: |---|---|---| | `system.health.summary` | resource | `apcore://system.health.summary` | | `system.health.module` | resource template | `apcore://system.health.module/{module_id}` | -| `system.usage.summary` | resource | `apcore://system.usage.summary{?period}` | +| `system.usage.summary` | resource | `apcore://system.usage.summary` | | `system.usage.module` | resource template | `apcore://system.usage.module/{module_id}{?period}` | | `system.manifest.full` | resource | `apcore://system.manifest.full` | | `system.manifest.module` | resource template | `apcore://system.manifest.module/{module_id}` | +| `system.manifest.search` | read-only tool | `system.manifest.search` | | `system.control.update_config` | tool | `system.control.update_config` | | `system.control.reload_module` | tool | `system.control.reload_module` | | `system.control.toggle_feature` | tool | `system.control.toggle_feature` | +`resources/read` accepts an optional `?period=…` for both usage endpoints. Only the usage module +template advertises `{?period}`. + A `resources/read` on any `apcore://system.*` URI **MUST** be dispatched through the same execution path (Activation → ACL → Approval → Executor pipeline) as a `tools/call` on the corresponding module — an adapter **MUST NOT** add a second, resource-only invocation path that bypasses ACL or @@ -130,22 +133,20 @@ registry/module invocation. Nothing here changes ACL or Approval semantics. The three read-only groups (`health`, `usage`, `manifest`) are read-only, no-side-effect modules per PROTOCOL_SPEC §6.6.2 and are still subject to -ACL evaluation on every `resources/read`, exactly as they would be on a `tools/call` were they -projected as tools. The `control` group keeps its `requiresApproval` annotation and passes through the +ACL evaluation on every `resources/read` and on `tools/call` for `system.manifest.search`. The +`control` group keeps its `_meta.requiresApproval` annotation and passes through the Approval gate identically whether it is discovered via `tools/list` or invoked directly by a client that already knows its name from this extension's contract. Declaring this extension does **not** imply an ACL rule exists that permits reaching any of these -modules — see [`acl-builder`](https://github.com/aiperceivable/apcore-mcp/blob/main/README.md) rule-template guidance +modules — see [`acl-builder`](./acl-builder.md) rule-template guidance (aiperceivable/apcore-mcp#14) for the ACL configuration that actually gates this surface. ## Degradation behavior -Per SEP-2133's graceful-degradation requirement, a client that does not understand this extension -simply does not see the `com.aiperceivable/management` key in `capabilities.extensions` and falls back -to core MCP discovery (`resources/list`, `resources/templates/list`, `tools/list`) to find the same -modules. No fallback code path is required on the client side because there is no behavior to fall -back *from* — the extension adds no protocol requirement, only a discovery shortcut. +Clients that omit or ignore the extension use ordinary MCP discovery (`resources/list`, +`resources/templates/list`, and `tools/list`) to find the same modules. The same Core activation, +ACL, and approval decisions apply in both cases. ## Security considerations @@ -168,8 +169,21 @@ back *from* — the extension adds no protocol requirement, only a discovery sho (regression test — proves the extension is not acting as a gate). - [ ] `surfaces` accurately reflects only the four groups actually registered on the running instance. -Phases B (Working Group discussion) and C (formal Extensions Track SEP against -`modelcontextprotocol/modelcontextprotocol`) are tracked by their own follow-ups when they start; see -aiperceivable/apcore-mcp#16 for the full three-phase plan and its gating requirements (a reference -implementation inside an official MCP SDK, and named Extension Maintainers, before SEP review can -begin). +## Reference implementation for #113 + +The example under `mcp/examples/management-reference` uses the official MCP Python SDK's discovery +and legacy handshake handlers. It exposes the management projection over stdio and uses the existing +Core Executor with a host-selected demo identity. + +- With `--advertise-management` and registered groups, both protocol eras advertise the same + extension settings. The example defaults to ordinary discovery and omits the entry when no + management groups are registered. SDK 2.3.0's legacy serializer omits `capabilities.extensions`. + The reference uses SDK middleware to preserve the Phase A entry after `initialize` serialization. +- Acceptance covers the shared projection fixture, a permitted and denied resource read, a denied + control call, and an ACL-permitted control call with missing, rejecting, and approving Core + handlers. An approved toggle changes subsequent module activation in the demo process. + +The Surfaces example supplies local evidence for Phase B. Under +[SEP-2133](https://modelcontextprotocol.io/seps/2133-extensions) and +[SEP-3392](https://modelcontextprotocol.io/seps/3392-extension-lifecycle), Phase C still needs a +reference in an official SDK codebase, a Working Group, named Extension Maintainers, and SEP review. diff --git a/mcp/examples/management-reference/.gitignore b/mcp/examples/management-reference/.gitignore new file mode 100644 index 00000000..49c413ad --- /dev/null +++ b/mcp/examples/management-reference/.gitignore @@ -0,0 +1,3 @@ +.venv/ +.venv-legacy/ +__pycache__/ diff --git a/mcp/examples/management-reference/README.md b/mcp/examples/management-reference/README.md new file mode 100644 index 00000000..370b3b65 --- /dev/null +++ b/mcp/examples/management-reference/README.md @@ -0,0 +1,51 @@ +# System Management Extension reference + +This stand-alone stdio example validates part of +[#113](https://github.com/aiperceivable/apcore-surfaces/issues/113) using the official MCP Python SDK +2.3.0 and the Core 1.0.0b1 candidate. See the +[extension contract](../../docs/features/system-management-extension.md). + +## Run the checks + +From this directory, use Python 3.12 and the Core beta candidate wheel if the package is unavailable +from your package index. + +```sh +uv venv --python 3.12 .venv +uv pip install --python .venv/bin/python -r requirements-test.txt /path/to/apcore-1.0.0b1-py3-none-any.whl +.venv/bin/python -m pytest -q +``` + +The same tests run through `server/discover` on MCP 2026-07-28 and `initialize` on MCP +2025-11-25. They check the shared projection fixture, ordinary discovery with extension +advertisement off, resource ACL, and control ACL and approval. For a second check with the actual +1.x client, use a separate environment. + +```sh +uv venv --python 3.12 .venv-legacy +uv pip install --python .venv-legacy/bin/python 'mcp==1.30.0' +.venv-legacy/bin/python legacy_smoke.py "$PWD/.venv/bin/python" +``` + +## Try the stdio server + +Configure a local MCP host to launch this command. + +```sh +.venv/bin/python server.py --advertise-management +``` + +- `--advertise-management` enables discovery of `com.aiperceivable/management` when groups are + registered. Plain MCP lists and calls are available independently of this flag. +- `--enable-control` registers the control tools. The host selects the demo role with `--role`. + `reader` is the default, `operator` can attempt the toggle tool, and `denied` demonstrates ACL denial. +- `--demo-approval` selects a deterministic Core handler for the demo. `missing` is the default and + fails closed, `deny` explicitly rejects, and `allow` simulates an approval. Control state and audit + data live in the local process. + +The SDK serves `server/discover` and owns the legacy handshake. SDK 2.3.0 removes +`capabilities.extensions` during legacy serialization, so the example uses SDK middleware to +preserve the Phase A entry on the legacy response. Both resource and tool invocations use the same +Core Executor and the identity selected at server startup. + +The example lives in Surfaces. Phase C requires a reference in an official MCP SDK codebase. diff --git a/mcp/examples/management-reference/legacy_smoke.py b/mcp/examples/management-reference/legacy_smoke.py new file mode 100644 index 00000000..db443a82 --- /dev/null +++ b/mcp/examples/management-reference/legacy_smoke.py @@ -0,0 +1,42 @@ +"""Connect an official MCP 1.x client to the SDK 2.x reference over stdio.""" + +import argparse +import json +from pathlib import Path + +import anyio +from mcp.client.stdio import stdio_client +from pydantic import AnyUrl + +from mcp import ClientSession, StdioServerParameters + + +async def verify(server_python: str) -> None: + server = Path(__file__).with_name("server.py").resolve() + params = StdioServerParameters( + command=server_python, + args=[str(server), "--advertise-management", "--enable-control", "--role", "operator"], + ) + with anyio.fail_after(15): + async with stdio_client(params) as (read, write), ClientSession(read, write) as session: + handshake = await session.initialize() + assert handshake.protocolVersion == "2025-11-25" + assert handshake.capabilities.extensions["com.aiperceivable/management"] == { + "surfaces": ["health", "usage", "manifest", "control"], + "protocolVersion": "1.30.0", + } + health = await session.read_resource(AnyUrl("apcore://system.health.summary")) + assert health.contents + result = await session.call_tool( + "system.control.toggle_feature", + {"module_id": "system.manifest.search", "enabled": False, "reason": "Legacy SDK smoke test"}, + ) + assert result.isError + assert json.loads(result.content[0].text) == {"code": "APPROVAL_DENIED"} + print("MCP 1.x client: initialize, extension settings, health read, and fail-closed approval passed") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("server_python", help="Path to the Python interpreter with the reference dependencies") + anyio.run(verify, parser.parse_args().server_python) diff --git a/mcp/examples/management-reference/requirements-test.txt b/mcp/examples/management-reference/requirements-test.txt new file mode 100644 index 00000000..2801b277 --- /dev/null +++ b/mcp/examples/management-reference/requirements-test.txt @@ -0,0 +1,3 @@ +apcore==1.0.0b1 +mcp==2.3.0 +pytest>=8,<10 diff --git a/mcp/examples/management-reference/server.py b/mcp/examples/management-reference/server.py new file mode 100644 index 00000000..1a94b04b --- /dev/null +++ b/mcp/examples/management-reference/server.py @@ -0,0 +1,215 @@ +"""Stdio reference for the unofficial MCP management extension.""" + +from __future__ import annotations + +import argparse +import json +from typing import Any +from urllib.parse import parse_qs, unquote, urlsplit + +import anyio +import mcp_types as types +from apcore import Context, Executor, Registry +from apcore.acl import ACL, ACLRule +from apcore.approval import AlwaysDenyHandler, AutoApproveHandler +from apcore.config import Config +from apcore.context import Identity +from apcore.errors import ModuleError +from apcore.sys_modules.audit import InMemoryAuditStore +from apcore.sys_modules.control import ToggleState +from apcore.sys_modules.registration import register_sys_modules +from mcp.server.context import CallNext, HandlerResult, ServerRequestContext +from mcp.server.lowlevel import Server +from mcp.server.stdio import stdio_server +from mcp.shared.exceptions import MCPError + +EXTENSION_ID = "com.aiperceivable/management" +GROUPS = ("health", "usage", "manifest", "control") +PROJECTION_VERSION = "1.30.0" +JSON_MIME = "application/json" +SEARCH = "system.manifest.search" +TOGGLE = "system.control.toggle_feature" + + +def management_server( + executor: Executor, + identity: Identity, + *, + advertise_extension: bool = False, +) -> Server: + resources: dict[str, types.Resource] = {} + templates: dict[str, types.ResourceTemplate] = {} + tools: dict[str, types.Tool] = {} + groups: set[str] = set() + + for module_id in executor.registry.list(prefix="system."): + _, _, suffix = module_id.partition(".") + group, separator, _ = suffix.partition(".") + if not separator or group not in GROUPS: + continue + definition = executor.registry.get_definition(module_id) + if definition is None: + continue + groups.add(group) + if group == "control" or module_id == SEARCH: + annotations = definition.annotations + tools[module_id] = types.Tool( + name=module_id, + description=definition.description, + input_schema=definition.input_schema, + output_schema=definition.output_schema, + annotations=types.ToolAnnotations( + read_only_hint=annotations.readonly, + destructive_hint=annotations.destructive, + idempotent_hint=annotations.idempotent, + open_world_hint=annotations.open_world, + ), + _meta={"requiresApproval": True} if annotations.requires_approval else None, + ) + elif module_id.endswith(".module"): + template = f"apcore://{module_id}/{{module_id}}" + if group == "usage": + template += "{?period}" + templates[module_id] = types.ResourceTemplate( + name=module_id, + uri_template=template, + mime_type=JSON_MIME, + ) + else: + resources[module_id] = types.Resource( + name=module_id, + uri=f"apcore://{module_id}", + mime_type=JSON_MIME, + ) + + async def invoke(module_id: str, arguments: dict[str, Any]) -> dict[str, Any]: + return await executor.call_async(module_id, arguments, context=Context.create(identity=identity)) + + async def list_tools(_ctx, _params): + return types.ListToolsResult(tools=list(tools.values())) + + async def list_resources(_ctx, _params): + return types.ListResourcesResult(resources=list(resources.values())) + + async def list_templates(_ctx, _params): + return types.ListResourceTemplatesResult(resource_templates=list(templates.values())) + + async def call_tool(_ctx, params: types.CallToolRequestParams) -> types.CallToolResult: + if params.name not in tools: + raise MCPError(types.INVALID_PARAMS, "Unknown management tool") + try: + output = await invoke(params.name, params.arguments or {}) + except ModuleError as exc: + return types.CallToolResult( + content=[types.TextContent(type="text", text=json.dumps({"code": exc.code}))], + is_error=True, + ) + return types.CallToolResult( + content=[types.TextContent(type="text", text=json.dumps(output))], + structured_content=output, + ) + + async def read_resource(_ctx, params: types.ReadResourceRequestParams) -> types.ReadResourceResult: + try: + uri = urlsplit(params.uri) + except ValueError as exc: + raise MCPError(types.INVALID_PARAMS, "Invalid management resource URI") from exc + module_id = uri.netloc + arguments = {} + if uri.scheme == "apcore" and module_id in templates and uri.path.lstrip("/"): + arguments["module_id"] = unquote(uri.path.lstrip("/")) + elif uri.scheme != "apcore" or module_id not in resources or uri.path not in ("", "/"): + raise MCPError(types.INVALID_PARAMS, "Unknown management resource") + period = parse_qs(uri.query).get("period") + if period and module_id in ("system.usage.summary", "system.usage.module"): + arguments["period"] = period[0] + try: + output = await invoke(module_id, arguments) + except ModuleError as exc: + raise MCPError(-32000, "Management resource read failed", {"code": exc.code}) from exc + return types.ReadResourceResult( + contents=[ + types.TextResourceContents(uri=params.uri, mime_type=JSON_MIME, text=json.dumps(output)), + ] + ) + + server = Server( + "apcore-management-reference", + version="0.1.0", + on_list_tools=list_tools if tools else None, + on_call_tool=call_tool if tools else None, + on_list_resources=list_resources if resources or templates else None, + on_list_resource_templates=list_templates if templates else None, + on_read_resource=read_resource if resources or templates else None, + ) + if advertise_extension and groups: + settings = { + "surfaces": [group for group in GROUPS if group in groups], + "protocolVersion": PROJECTION_VERSION, + } + server.extensions[EXTENSION_ID] = settings + + async def preserve_legacy_extension(ctx: ServerRequestContext, call_next: CallNext) -> HandlerResult: + result = await call_next(ctx) + # SDK 2.3.0's legacy serializer drops extensions. Preserve the + # Phase A entry after the SDK has handled the initialize request. + if ctx.method == "initialize" and isinstance(result, dict): + result["capabilities"].setdefault("extensions", {}).setdefault(EXTENSION_ID, settings) + return result + + server.middleware.append(preserve_legacy_extension) + return server + + +async def serve(args: argparse.Namespace) -> None: + identity = Identity(id=f"reference-{args.role}", roles=(args.role,)) + rules = [ + ACLRule( + callers=["@external"], + targets=["system.health.*", "system.usage.*", "system.manifest.*"], + effect="allow", + conditions={"roles": ["reader", "operator"]}, + ), + ACLRule( + callers=["@external"], + targets=[TOGGLE], + effect="allow", + conditions={"roles": ["operator"]}, + ), + ] + approval = {"missing": None, "deny": AlwaysDenyHandler(), "allow": AutoApproveHandler()} + config = Config( + data={ + "sys_modules": {"enabled": not args.disable_management, "events": {"enabled": args.enable_control}}, + } + ) + registry = Registry() + toggle_state = ToggleState() + executor = Executor( + registry=registry, + acl=ACL(rules=rules, default_effect="deny"), + config=config, + approval_handler=approval[args.demo_approval], + toggle_state=toggle_state, + ) + register_sys_modules( + registry=registry, + executor=executor, + config=config, + fail_on_error=True, + audit_store=InMemoryAuditStore(), + toggle_state=toggle_state, + ) + server = management_server(executor, identity, advertise_extension=args.advertise_management) + async with stdio_server() as (read_stream, write_stream): + await server.run(read_stream, write_stream, server.create_initialization_options()) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--advertise-management", action="store_true") + parser.add_argument("--disable-management", action="store_true") + parser.add_argument("--enable-control", action="store_true") + parser.add_argument("--role", choices=("reader", "operator", "denied"), default="reader") + parser.add_argument("--demo-approval", choices=("missing", "deny", "allow"), default="missing") + anyio.run(serve, parser.parse_args()) diff --git a/mcp/examples/management-reference/test_management_reference.py b/mcp/examples/management-reference/test_management_reference.py new file mode 100644 index 00000000..dca6540d --- /dev/null +++ b/mcp/examples/management-reference/test_management_reference.py @@ -0,0 +1,131 @@ +"""Drive the official client and reference server over JSON-RPC stdio.""" + +import json +import sys +from pathlib import Path + +import pytest +from mcp.client.stdio import StdioServerParameters +from mcp.shared.exceptions import MCPError + +from mcp import Client + +HERE = Path(__file__).resolve().parent +FIXTURE = json.loads((HERE.parents[1] / "conformance/fixtures/system_surface.json").read_text()) +EXTENSION = FIXTURE["extension"] +HEALTH = "apcore://system.health.summary" +SEARCH = "system.manifest.search" +TOGGLE = "system.control.toggle_feature" +TOGGLE_INPUT = {"module_id": SEARCH, "enabled": False, "reason": "Reference test"} + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +@pytest.fixture(params=[("auto", "2026-07-28"), ("legacy", "2025-11-25")]) +def connection(request): + mode, expected_version = request.param + + def connect(*args): + process = StdioServerParameters(command=sys.executable, args=[str(HERE / "server.py"), *args]) + return Client(process, mode=mode, read_timeout_seconds=10) + + return connect, expected_version + + +pytestmark = pytest.mark.anyio + + +@pytest.mark.parametrize( + ("args", "groups"), + [ + (("--advertise-management", "--enable-control"), EXTENSION["surface_order"]), + (("--advertise-management",), EXTENSION["surface_order"][:-1]), + (("--advertise-management", "--disable-management", "--enable-control"), []), + (("--enable-control",), []), + ], + ids=["full", "read-only", "disabled", "ordinary-discovery"], +) +async def test_discovery(connection, args, groups): + connect, expected_version = connection + async with connect(*args) as client: + assert client.protocol_version == expected_version + discover = client.session.discover_result + if expected_version == "2026-07-28": + assert expected_version in discover.supported_versions + else: + assert discover is None + + capabilities = client.server_capabilities + extension = (capabilities.extensions or {}).get(EXTENSION["identifier"]) + if groups: + assert extension == {"surfaces": groups, "protocolVersion": EXTENSION["protocol_version"]} + else: + assert extension is None + + if "--disable-management" in args: + assert capabilities.tools is None + assert capabilities.resources is None + return + + tools = {tool.name: tool for tool in (await client.list_tools()).tools} + expected_tools = {tool["name"] for tool in FIXTURE["tools"]} + if "--enable-control" in args: + assert tools.keys() == expected_tools + for name in expected_tools - {SEARCH}: + assert tools[name].meta["requiresApproval"] is True + else: + assert tools.keys() == {SEARCH} + assert tools[SEARCH].annotations.read_only_hint is True + assert not (tools[SEARCH].meta or {}).get("requiresApproval") + assert {resource.uri for resource in (await client.list_resources()).resources} == { + resource["uri"] for resource in FIXTURE["resources"] + } + assert {template.uri_template for template in (await client.list_resource_templates()).resource_templates} == { + template["uri_template"] for template in FIXTURE["resource_templates"] + } + assert (await client.read_resource(HEALTH)).contents + usage = await client.read_resource("apcore://system.usage.summary?period=1h") + assert json.loads(usage.contents[0].text)["period"] == "1h" + module = await client.read_resource(f"apcore://system.health.module/{SEARCH}") + assert json.loads(module.contents[0].text)["module_id"] == SEARCH + module_usage = await client.read_resource(f"apcore://system.usage.module/{SEARCH}?period=1h") + usage_data = json.loads(module_usage.contents[0].text) + assert (usage_data["module_id"], usage_data["period"]) == (SEARCH, "1h") + + +async def test_resource_acl_ignores_client_identity_claim(connection): + connect, _ = connection + async with connect("--advertise-management", "--role", "denied") as client: + with pytest.raises(MCPError) as error: + await client.read_resource(HEALTH, meta={"identity": {"id": "reference-reader", "roles": ["reader"]}}) + assert error.value.data == {"code": "ACL_DENIED"} + + +@pytest.mark.parametrize( + ("role", "decision", "error_code"), + [ + ("reader", "allow", "ACL_DENIED"), + ("operator", "missing", "APPROVAL_DENIED"), + ("operator", "deny", "APPROVAL_DENIED"), + ("operator", "allow", None), + ], +) +@pytest.mark.parametrize("advertisement", [(), ("--advertise-management",)], ids=["ordinary", "advertised"]) +async def test_control_governance(connection, role, decision, error_code, advertisement): + connect, _ = connection + # The host identity and Core approval verdict govern both discovery modes. + async with connect(*advertisement, "--enable-control", "--role", role, "--demo-approval", decision) as client: + result = await client.call_tool(TOGGLE, TOGGLE_INPUT) + search = await client.call_tool(SEARCH, {}) + if error_code: + assert result.is_error + assert json.loads(result.content[0].text) == {"code": error_code} + assert not search.is_error + else: + assert not result.is_error + assert result.structured_content == {"success": True, "module_id": SEARCH, "enabled": False} + assert search.is_error + assert json.loads(search.content[0].text) == {"code": "MODULE_DISABLED"}