From 33e4d6d864d163ae3f297e04454fcba28da1a584 Mon Sep 17 00:00:00 2001 From: tercel Date: Sat, 28 Nov 2026 20:14:35 +0800 Subject: [PATCH 1/2] feat(surfaces): bridge runtime interactions and pilot media links Signed-off-by: tercel --- .github/workflows/core-candidate.yml | 17 +- .github/workflows/rust.yml | 21 +- a2a/docs/features/adapters.md | 15 +- a2a/python/README.md | 6 + a2a/python/src/apcore_a2a/__init__.py | 4 + a2a/python/src/apcore_a2a/_serve.py | 5 + a2a/python/src/apcore_a2a/adapters/parts.py | 14 + a2a/python/src/apcore_a2a/artifacts.py | 200 +++++++++++++ a2a/python/src/apcore_a2a/server/executor.py | 38 ++- a2a/python/src/apcore_a2a/server/factory.py | 3 + .../tests/server/test_artifact_links.py | 200 +++++++++++++ mcp/docs/features/mcp-server-factory.md | 33 +++ mcp/python/src/apcore_mcp/__init__.py | 2 + mcp/python/src/apcore_mcp/apcore_mcp.py | 6 +- mcp/python/src/apcore_mcp/artifacts.py | 87 ++++++ mcp/python/src/apcore_mcp/helpers.py | 36 ++- .../apcore_mcp/server/async_task_bridge.py | 3 +- mcp/python/src/apcore_mcp/server/factory.py | 53 +++- mcp/python/src/apcore_mcp/server/router.py | 19 +- mcp/python/tests/server/test_artifact_wire.py | 78 +++++ .../tests/server/test_core_interactions.py | 95 +++++++ mcp/python/tests/test_artifacts.py | 32 +++ mcp/python/tests/test_review_fixes.py | 1 + mcp/rust/Cargo.lock | 5 +- mcp/rust/Cargo.toml | 3 +- mcp/rust/src/apcore_mcp.rs | 17 +- mcp/rust/src/artifact_wire_tests.rs | 153 ++++++++++ mcp/rust/src/artifacts.rs | 211 ++++++++++++++ mcp/rust/src/lib.rs | 4 + mcp/rust/src/server/factory.rs | 95 ++++++- mcp/rust/src/server/router.rs | 154 ++++++++-- mcp/rust/src/server/server.rs | 14 +- mcp/rust/src/server/session.rs | 4 + mcp/rust/src/server/transport.rs | 266 +++++++++++++++++- mcp/rust/src/server/types.rs | 49 ++++ mcp/typescript/src/apcore-mcp.ts | 4 + mcp/typescript/src/artifacts.ts | 98 +++++++ mcp/typescript/src/helpers.ts | 29 ++ mcp/typescript/src/index.ts | 8 +- .../src/server/async-task-bridge.ts | 15 +- mcp/typescript/src/server/factory.ts | 40 ++- mcp/typescript/src/server/router.ts | 11 +- .../tests/server/artifact-wire.test.ts | 79 ++++++ .../server/realtime-interactions.test.ts | 119 ++++++++ toolkit/rust/Cargo.toml | 2 +- 45 files changed, 2267 insertions(+), 81 deletions(-) create mode 100644 a2a/python/src/apcore_a2a/artifacts.py create mode 100644 a2a/python/tests/server/test_artifact_links.py create mode 100644 mcp/python/src/apcore_mcp/artifacts.py create mode 100644 mcp/python/tests/server/test_artifact_wire.py create mode 100644 mcp/python/tests/server/test_core_interactions.py create mode 100644 mcp/python/tests/test_artifacts.py create mode 100644 mcp/rust/src/artifact_wire_tests.rs create mode 100644 mcp/rust/src/artifacts.rs create mode 100644 mcp/typescript/src/artifacts.ts create mode 100644 mcp/typescript/tests/server/artifact-wire.test.ts create mode 100644 mcp/typescript/tests/server/realtime-interactions.test.ts diff --git a/.github/workflows/core-candidate.yml b/.github/workflows/core-candidate.yml index 29a788e5..5464363f 100644 --- a/.github/workflows/core-candidate.yml +++ b/.github/workflows/core-candidate.yml @@ -181,7 +181,7 @@ jobs: text = manifest.read_text() if text.count("1.0.0a5") != 1: raise ValueError(f"Unexpected Core dependency in {manifest}") - manifest.write_text(text.replace("1.0.0a5", "1.0.0a6")) + manifest.write_text(text.replace("1.0.0a5", "1.0.0b1")) PY fi args=(-e '.[dev]') @@ -204,7 +204,7 @@ jobs: import apcore import apcore_toolkit - from apcore import APCore, Executor + from apcore import APCore, Context, Executor from apcore.events import CircuitBreakerWrapper installed = distribution("apcore") @@ -216,12 +216,13 @@ 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.0a6" + assert installed.version == "1.0.0b1" 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)) assert callable(getattr(APCore, "stream_with_completion", None)) assert hasattr(CircuitBreakerWrapper, "retry") + assert callable(Context.report_progress) and callable(Context.elicit) else: assert installed.version == "0.33.0" PY @@ -342,7 +343,7 @@ jobs: import { readFileSync, realpathSync } from 'node:fs'; import { resolve, sep } from 'node:path'; import { fileURLToPath } from 'node:url'; - import { APCore, Executor } from 'apcore-js'; + import { APCore, Context, Executor } from 'apcore-js'; const core = realpathSync('./node_modules/apcore-js'); const coreEntry = realpathSync(fileURLToPath(import.meta.resolve('apcore-js'))); @@ -355,9 +356,11 @@ 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.6'); + assert.equal(coreVersion, '1.0.0-beta.1'); assert.equal(typeof Executor.prototype.streamWithCompletion, 'function'); assert.equal(typeof APCore.prototype.streamWithCompletion, 'function'); + assert.equal(typeof Context.prototype.reportProgress, 'function'); + assert.equal(typeof Context.prototype.elicit, 'function'); } else { assert.equal(coreVersion, '0.33.0'); } @@ -446,8 +449,8 @@ jobs: crate="${crates[0]}" version="${crate##*/apcore-}" version="${version%.crate}" - if [[ "$version" != 1.0.0-alpha.6 ]]; then - echo "Expected the alpha.6 Core crate." >&2 + if [[ "$version" != 1.0.0-beta.1 ]]; then + echo "Expected the beta.1 Core crate." >&2 exit 1 fi if [[ "$CORE_MODE" == candidate && -n "$EXPECTED_SHA256" ]]; then diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 93f1b3a7..f70c4692 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -25,6 +25,10 @@ env: CORE_REF: e4e2329de4ce8fa45669572ef9bd81c48da0d746 CORE_CRATE_VERSION: 1.0.0-alpha.5 CORE_CRATE_SHA256: 1d19939071ba2c589815c061dfb1ff827862e5f1f52251e88297d49eec500a90 + # MCP uses the native Context interactions from the paired Core candidate. + MCP_CORE_REF: 7573f0de32634e00ba0585d42094613c0add9a76 + MCP_CORE_CRATE_VERSION: 1.0.0-beta.1 + MCP_CORE_CRATE_SHA256: 8e7772ee85ac6d1a0538abe1766e6fb192e96a0b657bd05ebf65be60741f47ef jobs: source: @@ -48,7 +52,7 @@ jobs: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: repository: aiperceivable/apcore - ref: ${{ env.CORE_REF }} + ref: ${{ matrix.component == 'mcp' && env.MCP_CORE_REF || env.CORE_REF }} path: .ci-apcore-core persist-credentials: false - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 @@ -91,7 +95,7 @@ jobs: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: repository: aiperceivable/apcore - ref: ${{ env.CORE_REF }} + ref: ${{ matrix.component == 'mcp' && env.MCP_CORE_REF || env.CORE_REF }} path: .ci-apcore-core persist-credentials: false - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 @@ -103,13 +107,20 @@ jobs: shell: bash env: CARGO_TARGET_DIR: ${{ runner.temp }}/core-dependency-target + PINNED_CORE_VERSION: ${{ matrix.component == 'mcp' && env.MCP_CORE_CRATE_VERSION || env.CORE_CRATE_VERSION }} + PINNED_CORE_SHA256: ${{ matrix.component == 'mcp' && env.MCP_CORE_CRATE_SHA256 || env.CORE_CRATE_SHA256 }} run: | git rev-parse HEAD rustup toolchain install 1.86.0 --profile minimal # Core was already verified upstream. Reproduce the same archive. - cargo +1.86.0 package --locked --all-features --no-verify - archive="$CARGO_TARGET_DIR/package/apcore-$CORE_CRATE_VERSION.crate" - printf '%s %s\n' "$CORE_CRATE_SHA256" "$archive" | sha256sum --check + if [[ -f apcore-macros/Cargo.toml ]]; then + cargo +1.86.0 --config "patch.crates-io.apcore-macros.path='$PWD/apcore-macros'" \ + package --locked -p apcore --all-features --no-verify + else + cargo +1.86.0 package --locked --all-features --no-verify + fi + archive="$CARGO_TARGET_DIR/package/apcore-$PINNED_CORE_VERSION.crate" + printf '%s %s\n' "$PINNED_CORE_SHA256" "$archive" | sha256sum --check mkdir "$RUNNER_TEMP/core-dependency" tar -xzf "$archive" --strip-components=1 -C "$RUNNER_TEMP/core-dependency" - name: Package and verify the Surface crate diff --git a/a2a/docs/features/adapters.md b/a2a/docs/features/adapters.md index 80de1c5a..5fbecc23 100644 --- a/a2a/docs/features/adapters.md +++ b/a2a/docs/features/adapters.md @@ -532,7 +532,20 @@ Bidirectional converter between A2A Parts and apcore module inputs/outputs. > discriminator. Reading inspects the active oneof case (Python: > `part.WhichOneof("content")`; TypeScript: `part.content.$case`; Rust: the > `Part` enum variant). A "FilePart" corresponds to the `raw` (bytes) or `url` -> oneof case and is rejected as unsupported. +> oneof case and is rejected as unsupported on input. + +#### Hosted artifact links pilot + +Python hosts enable this pilot by passing `artifact_links=ArtifactLinkPolicy(resolve, {"downloads.example.com"})` +to `async_serve`, `serve`, or `A2AServerFactory.create`. Declare a direct, non-sensitive string property with +`x-a2a-artifact: true` in a unary module's output schema and return an opaque ID. The trusted asynchronous +resolver receives that ID and a snapshot of the authenticated `Identity`. It returns `HostedArtifact` +metadata for a download the caller is authorized to access, or `None` to omit the link. + +The adapter checks the exact HTTPS host allowlist, expiry in Unix seconds, and the link's size before +adding an A2A URL `Part` with filename and media type alongside the final validated data part. The size +cap defaults to 8 MiB and is configurable with `max_bytes`. The download host serves the bytes and +enforces the caller's authorization, expiry, and byte limit, including access from previously stored tasks. ## File Structure diff --git a/a2a/python/README.md b/a2a/python/README.md index 566c2a38..cb802f9d 100644 --- a/a2a/python/README.md +++ b/a2a/python/README.md @@ -289,3 +289,9 @@ pytest ## License Apache 2.0 — see [LICENSE](LICENSE). + + +### Hosted artifact links + +Python hosts can add authorized downloads to unary A2A results. +See [Hosted artifact links pilot](../docs/features/adapters.md#hosted-artifact-links-pilot). diff --git a/a2a/python/src/apcore_a2a/__init__.py b/a2a/python/src/apcore_a2a/__init__.py index ebf38b5b..6c3603ca 100644 --- a/a2a/python/src/apcore_a2a/__init__.py +++ b/a2a/python/src/apcore_a2a/__init__.py @@ -4,6 +4,7 @@ from apcore_a2a._serve import async_serve, serve from apcore_a2a.adapters import AgentCardBuilder, ErrorMapper, PartConverter, SchemaConverter, SkillMapper +from apcore_a2a.artifacts import ArtifactLinkPolicy, ArtifactResolver, HostedArtifact from apcore_a2a.auth import ( Authenticator, AuthMiddleware, @@ -42,6 +43,9 @@ "SchemaConverter", "ErrorMapper", "PartConverter", + "ArtifactLinkPolicy", + "ArtifactResolver", + "HostedArtifact", # Server "A2AServerFactory", "ApCoreAgentExecutor", diff --git a/a2a/python/src/apcore_a2a/_serve.py b/a2a/python/src/apcore_a2a/_serve.py index 6edf40e0..ccaf237c 100644 --- a/a2a/python/src/apcore_a2a/_serve.py +++ b/a2a/python/src/apcore_a2a/_serve.py @@ -11,6 +11,7 @@ from starlette.applications import Starlette from apcore_a2a._config import resolve_execution_timeout +from apcore_a2a.artifacts import ArtifactLinkPolicy from apcore_a2a.server.factory import A2AServerFactory logger = logging.getLogger(__name__) @@ -100,6 +101,7 @@ async def async_serve( metrics: bool = False, sys_modules: bool = False, disclose_refusal_reason: bool = False, + artifact_links: ArtifactLinkPolicy | None = None, ) -> Starlette: """Build and return a Starlette ASGI app for an A2A agent. @@ -188,6 +190,7 @@ async def async_serve( metrics=metrics, sys_modules=sys_modules, disclose_refusal_reason=disclose_refusal_reason, + artifact_links=artifact_links, ) # Step 7: Return the Starlette app @@ -216,6 +219,7 @@ def serve( metrics: bool = False, sys_modules: bool = False, disclose_refusal_reason: bool = False, + artifact_links: ArtifactLinkPolicy | None = None, ) -> None: """Launch an A2A agent server (blocking). @@ -284,6 +288,7 @@ async def _main() -> None: metrics=metrics, sys_modules=sys_modules, disclose_refusal_reason=disclose_refusal_reason, + artifact_links=artifact_links, ) config = uvicorn.Config( app, diff --git a/a2a/python/src/apcore_a2a/adapters/parts.py b/a2a/python/src/apcore_a2a/adapters/parts.py index 81e49108..80055a1f 100644 --- a/a2a/python/src/apcore_a2a/adapters/parts.py +++ b/a2a/python/src/apcore_a2a/adapters/parts.py @@ -11,6 +11,7 @@ from google.protobuf.json_format import MessageToDict, ParseDict from apcore_a2a.adapters.schema import SchemaConverter +from apcore_a2a.artifacts import ArtifactLinkPolicy, _ArtifactDeclaration class PartConverter: @@ -59,6 +60,19 @@ def parts_to_input(self, parts: list[Part], descriptor: Any) -> dict | str: raise ValueError("Empty or unknown part content") + async def add_artifact_links( + self, + artifact: Artifact, + output: Any, + declaration: _ArtifactDeclaration, + policy: ArtifactLinkPolicy, + ) -> None: + """Add authorized URL parts to an existing finalized data artifact.""" + if isinstance(output, dict) and declaration.is_current(): + parts = await policy._resolve_parts(output, declaration.fields, declaration.identity) + if declaration.is_current(): + artifact.parts.extend(parts) + def output_to_parts(self, output: Any, task_id: str = "") -> Artifact: """Convert apcore module output to a2a.types.Artifact. diff --git a/a2a/python/src/apcore_a2a/artifacts.py b/a2a/python/src/apcore_a2a/artifacts.py new file mode 100644 index 00000000..5accd451 --- /dev/null +++ b/a2a/python/src/apcore_a2a/artifacts.py @@ -0,0 +1,200 @@ +"""Opt-in hosted download links for finalized A2A results.""" + +from __future__ import annotations + +import re +import time +from collections.abc import Awaitable, Callable, Iterable +from copy import deepcopy +from dataclasses import dataclass +from typing import Any +from urllib.parse import urlsplit + +from a2a.types import Part +from apcore import Executor, Identity +from apcore.builtin_steps import BuiltinExecute, BuiltinOutputValidation + +_OPAQUE_ID = re.compile(r"[A-Za-z0-9_-]{1,128}") +_HOST = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:[.][a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*") +_MEDIA_TYPE = re.compile(r"[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*") +# Pilot support is limited to direct declarations. These schema applicators +# can place a second annotation on the same instance path. +_SCHEMA_APPLICATORS = frozenset( + {"$ref", "$dynamicRef", "allOf", "anyOf", "oneOf", "if", "then", "else", "dependentSchemas", "patternProperties"} +) + + +@dataclass(frozen=True, slots=True) +class HostedArtifact: + """An authorized download issued by the host, with expiry in Unix seconds.""" + + url: str + filename: str + media_type: str + size_bytes: int + expires_at: float + + +ArtifactResolver = Callable[[str, Identity], Awaitable[HostedArtifact | None]] + + +class ArtifactLinkPolicy: + """Ask a trusted host resolver for A2A links without fetching any content.""" + + def __init__(self, resolve: ArtifactResolver, allowed_hosts: Iterable[str], *, max_bytes: int = 8_388_608) -> None: + if not callable(resolve): + raise ValueError("Expected an artifact resolver") + if isinstance(allowed_hosts, str): + raise ValueError("Pass a collection of exact allowed hostnames") + candidates = tuple(allowed_hosts) + if not all(isinstance(host, str) for host in candidates): + raise ValueError("Artifact links require exact allowed hostnames") + hosts = frozenset(host.lower() for host in candidates) + if not hosts or any(len(host) > 253 or not _HOST.fullmatch(host) for host in hosts): + raise ValueError("Artifact links require exact allowed hostnames") + if type(max_bytes) is not int or max_bytes <= 0: + raise ValueError("Artifact link size limit must be a positive integer") + self._resolve = resolve + self._allowed_hosts = hosts + self._max_bytes = max_bytes + + def _is_allowed(self, artifact: HostedArtifact) -> bool: + return ( + type(artifact.size_bytes) is int + and 0 <= artifact.size_bytes <= self._max_bytes + and type(artifact.expires_at) in (int, float) + and time.time() < artifact.expires_at < float("inf") + and isinstance(artifact.filename, str) + and 0 < len(artifact.filename) <= 200 + and artifact.filename.isprintable() + and artifact.filename not in (".", "..") + and "/" not in artifact.filename + and chr(92) not in artifact.filename + and isinstance(artifact.media_type, str) + and len(artifact.media_type) <= 127 + and _MEDIA_TYPE.fullmatch(artifact.media_type) is not None + and self._is_allowed_url(artifact.url) + ) + + def _is_allowed_url(self, url: str) -> bool: + if not isinstance(url, str) or not 0 < len(url) <= 4096 or chr(92) in url: + return False + if not url.isascii() or any(not char.isprintable() or char.isspace() for char in url): + return False + try: + parts = urlsplit(url) + host = parts.hostname + except ValueError: + return False + return ( + parts.scheme == "https" + and host in self._allowed_hosts + and parts.netloc.lower() in (host, f"{host}:443") + and not parts.fragment + ) + + async def _resolve_parts(self, output: dict[str, Any], fields: tuple[str, ...], identity: Identity) -> list[Part]: + artifacts: list[HostedArtifact] = [] + unique_ids: set[str] = set() + for field in fields: + artifact_id = output.get(field) + if not isinstance(artifact_id, str) or not _OPAQUE_ID.fullmatch(artifact_id) or artifact_id in unique_ids: + continue + unique_ids.add(artifact_id) + try: + metadata = await self._resolve(artifact_id, identity) + except Exception: + continue # Do not expose resolver errors or signed URLs in task diagnostics. + if isinstance(metadata, HostedArtifact): + artifacts.append(metadata) + + return [ + Part(url=artifact.url, media_type=artifact.media_type, filename=artifact.filename) + for artifact in artifacts + if self._is_allowed(artifact) + ] + + +def _link_fields(schema: Any) -> tuple[str, ...]: + if not isinstance(schema, dict) or schema.get("type") != "object": + return () + if schema.get("x-sensitive") or not _SCHEMA_APPLICATORS.isdisjoint(schema): + return () + properties = schema.get("properties") + if not isinstance(properties, dict): + return () + return tuple( + name + for name, declaration in properties.items() + if isinstance(declaration, dict) + and declaration.get("type") == "string" + and declaration.get("x-a2a-artifact") is True + and not declaration.get("x-sensitive") + and _SCHEMA_APPLICATORS.isdisjoint(declaration) + ) + + +@dataclass(frozen=True, slots=True) +class _ArtifactDeclaration: + registry: Any + skill_id: str + registration: Any + schema: dict[str, Any] + fields: tuple[str, ...] + identity: Identity + + def is_current(self) -> bool: + try: + resolved = self.registry._resolve_registration(self.skill_id, None) + if resolved is not self.registration: + return False + descriptor = self.registry._describe_registration(self.skill_id, resolved, warn_deprecation=False) + return descriptor.output_schema == self.schema + except Exception: + return False + + +def _artifact_declaration( + registry: Any, executor: Any, skill_id: str, identity: Identity +) -> _ArtifactDeclaration | None: + """Use a stable declaration from the registry the Core executor actually uses.""" + if not isinstance(identity.id, str) or not identity.id: + return None + if not isinstance(executor, Executor) or executor.registry is not registry: + return None + try: + step_types = {type(step) for step in executor.current_strategy.steps} + if not {BuiltinExecute, BuiltinOutputValidation} <= step_types: + return None + registration = registry._resolve_registration(skill_id, None) + if registration is None or callable(getattr(registration.module, "stream", None)): + return None + descriptor = registry._describe_registration(skill_id, registration, warn_deprecation=False) + annotations = descriptor.annotations + streaming = ( + annotations.get("streaming") if isinstance(annotations, dict) else getattr(annotations, "streaming", False) + ) + schema = deepcopy(descriptor.output_schema) + fields = _link_fields(schema) + if streaming or not fields: + return None + return _ArtifactDeclaration(registry, skill_id, registration, schema, fields, deepcopy(identity)) + except Exception: + # Older Core or an unprovable declaration keeps ordinary output behavior. + return None + + +def _validated_output(trace: Any) -> bool: + """Ignore outputs recovered from a failure before final validation.""" + completed = set() + for step in trace.steps: + if step.name == "context_creation": + completed.clear() + if ( + not step.skipped + and not step.skip_reason + and step.result.action == "continue" + and step.result.explanation is None + ): + completed.add(step.name) + return {"execute", "output_validation", "return_result"} <= completed diff --git a/a2a/python/src/apcore_a2a/server/executor.py b/a2a/python/src/apcore_a2a/server/executor.py index e804de29..0bc2fcdc 100644 --- a/a2a/python/src/apcore_a2a/server/executor.py +++ b/a2a/python/src/apcore_a2a/server/executor.py @@ -31,6 +31,7 @@ # Imported at module level — no circular dependency (middleware.py does not import executor.py) from apcore_a2a.adapters.errors import GOVERNANCE_REFUSAL_CODES, carries_caller_detail, sanitize_message +from apcore_a2a.artifacts import ArtifactLinkPolicy, _artifact_declaration, _ArtifactDeclaration, _validated_output from apcore_a2a.auth.middleware import auth_identity_var from apcore_a2a.server.context import TASK_OWNER_KEY, TASK_SKILL_KEY, identity_of, scoped_owner @@ -93,6 +94,7 @@ def __init__( execution_timeout: int = 300, on_state_change: Callable[[str, str], None] | None = None, *, + artifact_links: ArtifactLinkPolicy | None = None, track_terminal_status: bool = False, load_task: Callable[[str, Any], Awaitable[Task | None]] | None = None, ) -> None: @@ -102,6 +104,7 @@ def __init__( self._registry = registry self._execution_timeout = execution_timeout self._on_state_change = on_state_change + self._artifact_links = artifact_links # Cache inspect.signature results keyed by stable method qualified name self._context_accepts_cache: dict[str, bool] = {} self._running: dict[_TaskKey, _TaskExecution] = {} @@ -287,7 +290,10 @@ async def _execute(self, context: RequestContext, event_queue: EventQueue, run: and (inspect.isasyncgenfunction(stream_fn) or inspect.iscoroutinefunction(stream_fn)) ) - if _can_stream: + declaration = None + if self._artifact_links is not None and isinstance(identity, Identity) and apcore_ctx is not None: + declaration = _artifact_declaration(self._registry, self._executor, skill_id, identity) + if _can_stream and declaration is None: await self._run_with_timeout( self._execute_streaming(context, event_queue, skill_id, inputs, apcore_ctx, context_id, stopped), context.task_id, @@ -295,7 +301,15 @@ async def _execute(self, context: RequestContext, event_queue: EventQueue, run: ) else: await self._run_with_timeout( - self._send_single(context, event_queue, skill_id, inputs, apcore_ctx, stopped), + self._send_single( + context, + event_queue, + skill_id, + inputs, + apcore_ctx, + stopped, + declaration=declaration, + ), context.task_id, run, ) @@ -474,15 +488,31 @@ async def _send_single( inputs: Any, apcore_ctx: Any, stopped: asyncio.Event, + *, + declaration: _ArtifactDeclaration | None = None, ) -> None: - output = await self._execute_single(skill_id, inputs, apcore_ctx) + trace = None + if declaration is not None: + output, trace = await self._executor.call_async_with_trace(skill_id, inputs, apcore_ctx) + else: + output = await self._execute_single(skill_id, inputs, apcore_ctx) + if stopped.is_set(): + return + artifact = self._part_converter.output_to_parts(output, context.task_id) + if ( + declaration is not None + and self._artifact_links is not None + and trace is not None + and _validated_output(trace) + ): + await self._part_converter.add_artifact_links(artifact, output, declaration, self._artifact_links) if stopped.is_set(): return await event_queue.enqueue_event( TaskArtifactUpdateEvent( task_id=context.task_id, context_id=context.context_id or context.task_id, - artifact=self._part_converter.output_to_parts(output, context.task_id), + artifact=artifact, last_chunk=True, ) ) diff --git a/a2a/python/src/apcore_a2a/server/factory.py b/a2a/python/src/apcore_a2a/server/factory.py index 2aab4e03..d600c574 100644 --- a/a2a/python/src/apcore_a2a/server/factory.py +++ b/a2a/python/src/apcore_a2a/server/factory.py @@ -52,6 +52,7 @@ from apcore_a2a.adapters.parts import PartConverter from apcore_a2a.adapters.schema import SchemaConverter from apcore_a2a.adapters.skill_mapper import SkillMapper +from apcore_a2a.artifacts import ArtifactLinkPolicy from apcore_a2a.server.context import ( TASK_OWNER_KEY, TASK_SKILL_KEY, @@ -460,6 +461,7 @@ def create( metrics: bool = False, sys_modules: bool = False, disclose_refusal_reason: bool = False, + artifact_links: ArtifactLinkPolicy | None = None, ) -> tuple[Starlette, AgentCard]: """Build ASGI app and AgentCard. Returns (app, agent_card). @@ -615,6 +617,7 @@ async def load_task(task_id: str, context: ServerCallContext) -> Task | None: registry, execution_timeout, on_state_change=on_state_change_cb, + artifact_links=artifact_links, track_terminal_status=True, load_task=load_task, ) diff --git a/a2a/python/tests/server/test_artifact_links.py b/a2a/python/tests/server/test_artifact_links.py new file mode 100644 index 00000000..a3872e4a --- /dev/null +++ b/a2a/python/tests/server/test_artifact_links.py @@ -0,0 +1,200 @@ +"""A2A artifact link pilot through the actual factory and Core execution.""" + +from __future__ import annotations + +import time +from dataclasses import replace +from typing import Annotated + +import pytest +from apcore import APCore, Identity, Middleware, ModuleAnnotations +from pydantic import BaseModel, Field +from starlette.testclient import TestClient + +from apcore_a2a import A2AServerFactory, ArtifactLinkPolicy, HostedArtifact + +_SKILL = "artifact.download" +_ALLOWED_URL = "https://downloads.example.test/signed?id=token" + + +class _Result(BaseModel): + artifact: Annotated[str, Field(json_schema_extra={"x-a2a-artifact": True})] + sensitive: Annotated[str, Field(json_schema_extra={"x-a2a-artifact": True, "x-sensitive": True})] + + +class _Authenticator: + def authenticate(self, headers: dict[str, str]) -> Identity | None: + token = headers.get("authorization", "").removeprefix("Bearer ") + return Identity(id=token, attrs={"authenticated": True}) if token else None + + def security_schemes(self) -> dict: + return {"bearer": {"type": "http", "scheme": "bearer"}} + + +def _call(app: TestClient, principal: str = "alice") -> list[dict]: + response = app.post( + "/", + headers={"Authorization": f"Bearer {principal}", "A2A-Version": "1.0"}, + json={ + "jsonrpc": "2.0", + "id": 1, + "method": "SendMessage", + "params": { + "message": { + "messageId": "request", + "role": "ROLE_USER", + "parts": [{"text": "{}"}], + "metadata": {"skillId": _SKILL}, + }, + }, + }, + ).json() + assert "result" in response, response + return response["result"]["task"]["artifacts"][0]["parts"] + + +@pytest.mark.parametrize("enabled", [False, True]) +def test_link_uses_governed_final_output_and_current_identity(enabled: bool) -> None: + core = APCore() + observed: list[tuple[str, str]] = [] + + @core.module(_SKILL, tags=["artifact"]) + def download() -> _Result: + return _Result(artifact="initial", sensitive="private") + + class FinalOutput(Middleware): + def after(self, module_id, inputs, output, context): + context.identity.attrs["authenticated"] = False + return {**output, "artifact": "final"} + + core.use(FinalOutput()) + + async def resolve(artifact_id: str, identity: Identity) -> HostedArtifact | None: + assert identity.attrs["authenticated"] is True + observed.append((artifact_id, identity.id)) + if identity.id == "alice": + return HostedArtifact(_ALLOWED_URL, "report.txt", "text/plain", 4, time.time() + 30) + return None + + policy = ArtifactLinkPolicy(resolve, {"downloads.example.test"}) if enabled else None + app, _ = A2AServerFactory().create( + core.registry, + core.executor, + name="Test", + description="d", + version="1", + url="https://agent.example.test", + auth=_Authenticator(), + artifact_links=policy, + ) + + with TestClient(app) as client: + data = {"data": {"artifact": "final", "sensitive": "private"}} + expected = [{"url": _ALLOWED_URL, "filename": "report.txt", "mediaType": "text/plain"}] if enabled else [] + assert _call(client) == [data, *expected] + assert _call(client, "bob") == [data] + assert observed == ([("final", "alice"), ("final", "bob")] if enabled else []) + + +@pytest.mark.parametrize( + "override", + [ + {"url": "file:///tmp/report.txt"}, + {"url": "https://downloads.example.test.evil.test/report"}, + {"url": "https://user@downloads.example.test/report"}, + {"expires_at": 0}, + {"size_bytes": 9}, + ], +) +def test_unsafe_or_expired_download_is_omitted(override: dict) -> None: + core = APCore() + + @core.module(_SKILL, tags=["artifact"]) + def download() -> _Result: + return _Result(artifact="download_1", sensitive="private") + + async def resolve(opaque_id: str, identity: Identity) -> HostedArtifact | None: + assert opaque_id == "download_1" + metadata = HostedArtifact(_ALLOWED_URL, "report.txt", "text/plain", 4, time.time() + 30) + return replace(metadata, **override) + + app, _ = A2AServerFactory().create( + core.registry, + core.executor, + name="Test", + description="d", + version="1", + url="https://agent.example.test", + auth=_Authenticator(), + artifact_links=ArtifactLinkPolicy(resolve, {"downloads.example.test"}, max_bytes=8), + ) + with TestClient(app) as client: + assert _call(client) == [{"data": {"artifact": "download_1", "sensitive": "private"}}] + + +def test_recovered_output_does_not_publish_a_link() -> None: + core = APCore() + observed: list[str] = [] + + @core.module(_SKILL, tags=["artifact"]) + def download() -> _Result: + raise ValueError("no result") + + class Recover(Middleware): + def on_error(self, module_id, inputs, error, context): + return {"artifact": "recovered"} + + core.use(Recover()) + + async def resolve(artifact_id: str, identity: Identity) -> HostedArtifact | None: + observed.append(artifact_id) + return HostedArtifact(_ALLOWED_URL, "report.txt", "text/plain", 4, time.time() + 30) + + app, _ = A2AServerFactory().create( + core.registry, + core.executor, + name="Test", + description="d", + version="1", + url="https://agent.example.test", + auth=_Authenticator(), + artifact_links=ArtifactLinkPolicy(resolve, {"downloads.example.test"}), + ) + with TestClient(app) as client: + assert _call(client) == [{"data": {"artifact": "recovered"}}] + assert observed == [] + + +def test_native_stream_chunks_remain_data_parts_only() -> None: + core = APCore() + + class Stream: + description = "Stream short data fragments" + tags = ["artifact"] + input_schema = {"type": "object"} + output_schema = _Result + annotations = ModuleAnnotations(streaming=True) + + async def execute(self, inputs, context): + raise AssertionError("The pilot must retain native streaming") + + async def stream(self, inputs, context): + yield {"artifact": "stream_one", "sensitive": "private"} + + core.register(_SKILL, Stream()) + + async def resolve(artifact_id: str, identity: Identity) -> HostedArtifact | None: + pytest.fail("The pilot must never request a URL for a stream chunk") + + app, _ = A2AServerFactory().create( + core.registry, + core.executor, + name="Test", + description="d", + version="1", + url="https://agent.example.test", + auth=_Authenticator(), + artifact_links=ArtifactLinkPolicy(resolve, {"downloads.example.test"}), + ) + with TestClient(app) as client: + assert _call(client) == [{"data": {"artifact": "stream_one", "sensitive": "private"}}] diff --git a/mcp/docs/features/mcp-server-factory.md b/mcp/docs/features/mcp-server-factory.md index 4caebb9c..58e55d34 100644 --- a/mcp/docs/features/mcp-server-factory.md +++ b/mcp/docs/features/mcp-server-factory.md @@ -157,6 +157,39 @@ adapts the router result into the protocol `CallToolResult`; Rust's optional See the normative [MCP tool result contract](https://modelcontextprotocol.io/specification/2025-06-18/server/tools) and [HTTP protocol version contract](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports). +### Runtime Progress and Elicitation + +When the Core context exposes interaction callbacks, an executing module +can report progress or request an elicitation response using that context. +The adapter sends progress when the tool request supplies a progress token, +and attaches elicitation when the client session supports it. Existing MCP +helper functions continue to work. In Rust the native callbacks are available +on Stdio and SSE, where the adapter can address a specific client session. + +### Bounded Media Resource Links + +An application can opt into media links by providing an `MCPArtifactStore`. +Use `APCoreMCP(..., artifact_store=store)` in Python, the `artifactStore` +option in TypeScript, or the Rust builder's `artifact_store(Arc::new(store))`. +Use the `put` method to store the bytes, a display filename, a MIME type, and +the authenticated owner. Return the opaque ID from a top-level string property +whose output schema includes `"x-mcp-artifact": true`. + +The adapter appends a native `resource_link` for a successful, validated +structured tool result on supported MCP versions. The same result still +contains its text and structured data. Fields marked sensitive and references +that are expired, unavailable, or owned by a different authority produce no +link. Clients fetch the bytes using `resources/read`. That request checks +the current authenticated authority again, including its active scopes. + +The in-process store defaults to 8 MiB per entry, 16 entries, and 300 seconds +of retention. A full store rejects new entries until room is available. +The store accepts only bytes supplied by the embedding application. It never +opens filesystem paths or fetches remote URLs. Links expire on process exit. + +Rust callers constructing a `CallToolResult` struct literal include a +`resource_links` vector. Use an empty vector for a text-only result. + ### Custom Middleware Injection The public `serve()` entry point accepts an optional user-supplied middleware list: diff --git a/mcp/python/src/apcore_mcp/__init__.py b/mcp/python/src/apcore_mcp/__init__.py index 8a9c1edf..f14f3add 100644 --- a/mcp/python/src/apcore_mcp/__init__.py +++ b/mcp/python/src/apcore_mcp/__init__.py @@ -30,6 +30,7 @@ _load_config_bus_overrides as _load_config_bus_overrides, # noqa: F401 - re-export for tests ) from apcore_mcp.approval_store import ApprovalScope, ApprovalStore, InMemoryApprovalStore, ScopedApprovalStore +from apcore_mcp.artifacts import MCPArtifactStore from apcore_mcp.auth import ( Authenticator, AuthMiddleware, @@ -68,6 +69,7 @@ register_mcp_formatter() __all__ = [ + "MCPArtifactStore", # Public API "APCoreMCP", "serve", diff --git a/mcp/python/src/apcore_mcp/apcore_mcp.py b/mcp/python/src/apcore_mcp/apcore_mcp.py index 582782fe..5308389a 100644 --- a/mcp/python/src/apcore_mcp/apcore_mcp.py +++ b/mcp/python/src/apcore_mcp/apcore_mcp.py @@ -35,6 +35,7 @@ _implements_mcp_scoped_approval, _MCPScopedApprovalGate, ) +from apcore_mcp.artifacts import MCPArtifactStore from apcore_mcp.auth.protocol import Authenticator from apcore_mcp.server.transport import MetricsExporter @@ -407,6 +408,7 @@ def __init__( approval_handler: object | None = None, approval_store: object | None = None, approval_notify: object | None = None, + artifact_store: MCPArtifactStore | None = None, output_formatter: Callable[[dict], str] | None = None, output_format: str | None = None, strategy: str | None = None, @@ -450,6 +452,7 @@ def __init__( require_auth: If True, unauthenticated requests receive 401. exempt_paths: Exact paths that bypass authentication. approval_handler: Optional approval handler for runtime approval support. + artifact_store: Optional bounded store for MCP media resource links. output_formatter: Optional callable that formats dict results into text for LLM consumption. Defaults to ``None`` (raw JSON). output_format: Optional built-in output format name ("json", "csv", @@ -653,6 +656,7 @@ def __init__( self._async_bridge: Any = None self._approval_handler = approval_handler self._approval_store = approval_store + self._artifact_store = artifact_store self._output_formatter = output_formatter self._output_format = output_format @@ -715,7 +719,7 @@ def _build_server_components(self) -> tuple[Any, Any, list, Any, str]: version = self._resolve_version() - factory = MCPServerFactory() + factory = MCPServerFactory(artifact_store=self._artifact_store) if self._artifact_store else MCPServerFactory() server = factory.create_server(name=self._name, version=version) discovery_sources: dict[int, str] = {} tools = factory.build_tools( diff --git a/mcp/python/src/apcore_mcp/artifacts.py b/mcp/python/src/apcore_mcp/artifacts.py new file mode 100644 index 00000000..d12735c3 --- /dev/null +++ b/mcp/python/src/apcore_mcp/artifacts.py @@ -0,0 +1,87 @@ +"""In-process MCP media references owned by a trusted application.""" + +from __future__ import annotations + +import math +import re +from dataclasses import dataclass +from threading import Lock +from time import monotonic +from uuid import uuid4 + +from apcore import Identity + +ARTIFACT_URI_PREFIX = "apcore-artifact://" +_ARTIFACT_ID = re.compile("[a-f0-9]{32}") +_MEDIA_TYPE = re.compile(r"[a-zA-Z0-9!#$&^_.+-]+/[a-zA-Z0-9!#$&^_.+-]+") + + +def _authority(identity: Identity) -> tuple[str | None, str, str, tuple[str, ...], str | None]: + return identity.issuer, identity.type, identity.id, tuple(sorted(identity.roles)), identity.authority_key() + + +@dataclass(frozen=True, slots=True) +class _Artifact: + content: bytes + name: str + mime_type: str + owner: tuple[str | None, str, str, tuple[str, ...], str | None] + expires_at: float + + +class MCPArtifactStore: + """Bounded byte store for an opted-in MCP host.""" + + def __init__(self, *, max_bytes: int = 8_388_608, max_entries: int = 16, ttl_seconds: float = 300) -> None: + if type(max_bytes) is not int or max_bytes < 1: + raise ValueError("Artifact size limit must be a positive integer") + if type(max_entries) is not int or max_entries < 1: + raise ValueError("Artifact entry limit must be a positive integer") + if type(ttl_seconds) not in (int, float) or not math.isfinite(ttl_seconds) or ttl_seconds <= 0: + raise ValueError("Artifact expiry must be positive and finite") + self._max_bytes = max_bytes + self._max_entries = max_entries + self._ttl_seconds = ttl_seconds + self._items: dict[str, _Artifact] = {} + self._lock = Lock() + + def put(self, content: bytes, *, name: str, mime_type: str, owner: Identity) -> str: + """Register in-memory bytes for the current trusted authority.""" + if type(content) is not bytes or len(content) > self._max_bytes: + raise ValueError("Artifact content must be bytes within the size limit") + if not name or len(name) > 200 or any(char in name for char in ("/", chr(92))) or not name.isprintable(): + raise ValueError("Artifact name must be a printable filename") + if len(mime_type) > 127 or not _MEDIA_TYPE.fullmatch(mime_type): + raise ValueError("Artifact MIME type is invalid") + if not isinstance(owner, Identity) or not owner.id: + raise ValueError("An authenticated artifact owner is required") + authority = _authority(owner) + with self._lock: + now = monotonic() + expired = [key for key, artifact in self._items.items() if artifact.expires_at <= now] + for key in expired: + del self._items[key] + if len(self._items) >= self._max_entries: + raise ValueError("Artifact store is full") + key = uuid4().hex + self._items[key] = _Artifact(content, name, mime_type, authority, now + self._ttl_seconds) + return key + + def read_uri(self, uri: str, identity: Identity | None) -> _Artifact | None: + """Return a live artifact only for the authority that registered it.""" + if identity is None or not uri.startswith(ARTIFACT_URI_PREFIX): + return None + key = uri.removeprefix(ARTIFACT_URI_PREFIX) + if not _ARTIFACT_ID.fullmatch(key): + return None + authority = _authority(identity) + with self._lock: + artifact = self._items.get(key) + if artifact is None: + return None + if artifact.expires_at <= monotonic(): + del self._items[key] + return None + if artifact.owner != authority: + return None + return artifact diff --git a/mcp/python/src/apcore_mcp/helpers.py b/mcp/python/src/apcore_mcp/helpers.py index 0c82a6f6..79c713bf 100644 --- a/mcp/python/src/apcore_mcp/helpers.py +++ b/mcp/python/src/apcore_mcp/helpers.py @@ -7,12 +7,46 @@ from __future__ import annotations -from typing import Any, Literal, NotRequired, TypedDict +from typing import Any, Literal, NotRequired, TypedDict, TypeVar + +import apcore # Keys under context.data where MCP callbacks are stored. MCP_PROGRESS_KEY = "_mcp_progress" MCP_ELICIT_KEY = "_mcp_elicit" +_Context = TypeVar("_Context") + + +def _bind_core_progress(context: _Context) -> _Context: + """Attach the existing MCP sink to a native Core context when supported.""" + callback = getattr(context, "data", {}).get(MCP_PROGRESS_KEY) + bind = getattr(context, "with_progress_reporter", None) + if callback is None or not callable(bind): + return context + return bind(callback) + + +def _bind_core_elicitation(context: _Context) -> _Context: + """Translate the existing MCP result for a native Core context.""" + callback = getattr(context, "data", {}).get(MCP_ELICIT_KEY) + bind = getattr(context, "with_elicitation_handler", None) + result_type = getattr(apcore, "ElicitationResult", None) + if callback is None or not callable(bind) or not callable(result_type): + return context + + async def handle(message: str, requested_schema: dict[str, Any] | None) -> Any: + result = await callback(message, requested_schema) + if result is not None: + action, content = result["action"], result.get("content") + if action == "accept" and isinstance(content, dict): + return result_type("accept", content) + if action == "decline": + return result_type("decline") + return result_type("cancel") + + return bind(handle) + class ElicitResult(TypedDict): """Typed result from an MCP elicitation request. diff --git a/mcp/python/src/apcore_mcp/server/async_task_bridge.py b/mcp/python/src/apcore_mcp/server/async_task_bridge.py index ccbcd5a1..b0e78bf7 100644 --- a/mcp/python/src/apcore_mcp/server/async_task_bridge.py +++ b/mcp/python/src/apcore_mcp/server/async_task_bridge.py @@ -26,7 +26,7 @@ from mcp import types as mcp_types from apcore_mcp.adapters.errors import ErrorMapper -from apcore_mcp.helpers import MCP_PROGRESS_KEY +from apcore_mcp.helpers import MCP_PROGRESS_KEY, _bind_core_progress logger = logging.getLogger(__name__) @@ -272,6 +272,7 @@ async def _submit_with_progress( # route through MCP notifications/progress. if context is not None and progress_token is not None and send_notification is not None: self._install_progress_sink(context, progress_token, send_notification) + context = _bind_core_progress(context) if owner is None: task_id = await self._manager.submit(module_id, arguments, context) else: diff --git a/mcp/python/src/apcore_mcp/server/factory.py b/mcp/python/src/apcore_mcp/server/factory.py index e3c67d8a..1f2dac40 100644 --- a/mcp/python/src/apcore_mcp/server/factory.py +++ b/mcp/python/src/apcore_mcp/server/factory.py @@ -27,6 +27,7 @@ import apcore_mcp.markdown as _markdown from apcore_mcp.adapters.annotations import AnnotationMapper +from apcore_mcp.artifacts import ARTIFACT_URI_PREFIX, MCPArtifactStore from apcore_mcp.auth.middleware import _REQUEST_IDENTITY_KEY, auth_identity_var from apcore_mcp.server.approval_bridge import ApprovalBridge, _approval_response_log, _protect_sdk_approval_logs from apcore_mcp.server.async_task_bridge import RESERVED_PREFIX, AsyncTaskBridge @@ -263,7 +264,14 @@ def _build_call_result( class MCPServerFactory: """Creates and configures MCP Server instances from apcore Registry.""" - def __init__(self, *, strict: bool = True, rich_description: bool = False) -> None: + def __init__( + self, + *, + strict: bool = True, + rich_description: bool = False, + artifact_store: MCPArtifactStore | None = None, + ) -> None: + self._artifact_store = artifact_store # When ``rich_description`` is True, MCP Tool descriptions are # rendered as apcore-toolkit Markdown (title, description, # behavior table, schemas, examples) instead of the plain @@ -790,7 +798,10 @@ async def send_notification(notification: dict[str, Any]) -> 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) + result = _build_call_result(text_contents, is_error, output_schema, approval=pending_approval) + if regular_tool and not background_tool: + self._attach_artifact_links(result, output_schema, identity) + return result sdk_call_tool = server.request_handlers[mcp_types.CallToolRequest] @@ -924,6 +935,11 @@ async def handle_list_resource_templates() -> list[mcp_types.ResourceTemplate]: @server.read_resource() async def handle_read_resource(uri: Any) -> list[ReadResourceContents]: uri_str = str(uri) + if self._artifact_store is not None and uri_str.startswith(ARTIFACT_URI_PREFIX): + artifact = self._artifact_store.read_uri(uri_str, _request_identity()) + if artifact is None: + raise ValueError("Artifact not found") + return [ReadResourceContents(content=artifact.content, mime_type=artifact.mime_type)] docs_prefix = "docs://" system_prefix = f"{_SYSTEM_RESOURCE_SCHEME}://system." if uri_str.startswith(system_prefix): @@ -936,6 +952,39 @@ async def handle_read_resource(uri: Any) -> list[ReadResourceContents]: raise ValueError(f"Resource not found: {uri_str}") return [ReadResourceContents(content=documentation, mime_type="text/plain")] + def _attach_artifact_links( + self, + result: mcp_types.CallToolResult, + schema: dict[str, Any] | None, + identity: Identity | None, + ) -> None: + store = self._artifact_store + if store is None or result.isError or result.structuredContent is None or schema is None: + return + properties = schema.get("properties") + if not isinstance(properties, dict): + return + emitted: set[str] = set() + for name, definition in properties.items(): + if not isinstance(definition, dict) or definition.get("x-mcp-artifact") is not True: + continue + if definition.get("x-sensitive") is True: + continue + key = result.structuredContent.get(name) + if not isinstance(key, str) or len(key) != 32 or key in emitted: + continue + uri = ARTIFACT_URI_PREFIX + key + artifact = store.read_uri(uri, identity) + if artifact is not None: + emitted.add(key) + result.content.append(mcp_types.ResourceLink( + type="resource_link", + uri=AnyUrl(uri), + name=artifact.name, + mimeType=artifact.mime_type, + size=len(artifact.content), + )) + async def _read_system_resource( self, uri: Any, diff --git a/mcp/python/src/apcore_mcp/server/router.py b/mcp/python/src/apcore_mcp/server/router.py index e88df7ba..c6e4dcd3 100644 --- a/mcp/python/src/apcore_mcp/server/router.py +++ b/mcp/python/src/apcore_mcp/server/router.py @@ -18,10 +18,13 @@ from apcore.registry.types import ModuleDescriptor from apcore.registry.version import matches_version_hint from apcore.trace_context import TraceContext, TraceParent +from mcp import types as mcp_types +from mcp.server.lowlevel.server import request_ctx +from mcp.server.session import ServerSession from apcore_mcp.adapters.approval import _capture_pending_error from apcore_mcp.adapters.errors import ErrorMapper -from apcore_mcp.helpers import MCP_ELICIT_KEY, MCP_PROGRESS_KEY +from apcore_mcp.helpers import MCP_ELICIT_KEY, MCP_PROGRESS_KEY, _bind_core_elicitation, _bind_core_progress logger = logging.getLogger(__name__) @@ -561,6 +564,10 @@ async def _progress_callback( # Inject elicitation callback if session available if session is not None: _session = session + request = request_ctx.get(None) + related = {} + if request is not None and request.session is session: + related["related_request_id"] = request.request_id async def _elicit_callback( message: str, @@ -570,6 +577,7 @@ async def _elicit_callback( result = await _session.elicit_form( message=message, requestedSchema=requested_schema or {}, + **related, ) return { "action": result.action, @@ -611,6 +619,15 @@ async def _elicit_callback( cancel_token=cancel_token, ) + context = _bind_core_progress(context) + if session is not None and ( + not isinstance(session, ServerSession) + or session.check_client_capability( + mcp_types.ClientCapabilities(elicitation=mcp_types.ElicitationCapability()) + ) + ): + context = _bind_core_elicitation(context) + # Explicit SDK hint, then MCP metadata, then descriptor default. version_hint = _request_version_hint(extra) descriptor = None diff --git a/mcp/python/tests/server/test_artifact_wire.py b/mcp/python/tests/server/test_artifact_wire.py new file mode 100644 index 00000000..f8b3f9b7 --- /dev/null +++ b/mcp/python/tests/server/test_artifact_wire.py @@ -0,0 +1,78 @@ +"""Exercise the opted-in artifact pilot through the MCP HTTP entry point.""" + +from __future__ import annotations + +import base64 +import json + +import httpx +from apcore import ACL, ACLRule, Executor, Identity, Registry + +from apcore_mcp import APCoreMCP, MCPArtifactStore +from tests.server.test_scoped_approval_wire import _HttpSession + + +async def test_tool_link_and_binary_read_require_the_registered_authority(): + owner = Identity("owner", "agent", issuer="test", scopes=("render",)) + guest = Identity("guest", "agent", issuer="test", scopes=("render",)) + store = MCPArtifactStore(max_bytes=1024) + artifact_id = store.put(b"image bytes", name="preview.png", mime_type="image/png", owner=owner) + + class Authenticator: + def authenticate(self, headers): + return {"Bearer owner": owner, "Bearer guest": guest}.get(headers.get("authorization")) + + class Preview: + description = "Return a generated preview" + input_schema = {"type": "object", "properties": {}} + output_schema = { + "type": "object", + "properties": {"artifact": {"type": "string", "x-mcp-artifact": True}}, + "required": ["artifact"], + } + + async def execute(self, _inputs, _context): + return {"artifact": artifact_id} + + registry = Registry() + registry.register("media.preview", Preview()) + acl = ACL( + [ACLRule(callers=["@external"], targets=["media.preview"], effect="allow", conditions={"scopes": ["render"]})], + default_effect="deny", + ) + mcp = APCoreMCP( + Executor(registry, acl=acl), authenticator=Authenticator(), artifact_store=store, async_tasks=False, + ) + async with mcp.async_serve() as app, httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://localhost", + ) as client: + owner_session = _HttpSession(client, "Bearer owner") + guest_session = _HttpSession(client, "Bearer guest") + await owner_session.initialize() + await guest_session.initialize() + call = {"name": "media.preview", "arguments": {}} + result = await owner_session.request("tools/call", call) + assert not result["isError"] + assert result["structuredContent"] == {"artifact": artifact_id} + assert json.loads(result["content"][0]["text"]) == {"artifact": artifact_id} + link = result["content"][1] + assert link["type"] == "resource_link" + assert link["name"] == "preview.png" + assert link["mimeType"] == "image/png" + assert "blob" not in link + + read = {"uri": link["uri"]} + binary = (await owner_session.request("resources/read", read))["contents"][0] + assert binary["mimeType"] == "image/png" + assert base64.b64decode(binary["blob"]) == b"image bytes" + + guest_result = await guest_session.request("tools/call", call) + assert [item["type"] for item in guest_result["content"]] == ["text"] + denied = await client.post("/mcp/", headers=guest_session.headers, json={ + "jsonrpc": "2.0", "method": "resources/read", "params": read, "id": 99, + }) + 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 "blob" not in denied.text diff --git a/mcp/python/tests/server/test_core_interactions.py b/mcp/python/tests/server/test_core_interactions.py new file mode 100644 index 00000000..f649705b --- /dev/null +++ b/mcp/python/tests/server/test_core_interactions.py @@ -0,0 +1,95 @@ +"""Verify Core callbacks through MCP, with legacy versions kept importable.""" + +from typing import Any + +import anyio +import pytest +from apcore import Context, Executor, Registry +from mcp import ClientSession, types +from pydantic import BaseModel + +from apcore_mcp.server.async_task_bridge import AsyncTaskBridge +from apcore_mcp.server.factory import MCPServerFactory +from apcore_mcp.server.router import ExecutionRouter +from apcore_mcp.server.transport import TransportManager + +pytestmark = pytest.mark.skipif( + not hasattr(Context, "with_progress_reporter") or not hasattr(Context, "with_elicitation_handler"), + reason="Installed Core has no native interaction callbacks", +) + + +class _Inputs(BaseModel): + pass + + +@pytest.mark.asyncio +@pytest.mark.parametrize("supports_elicitation", [True, False]) +async def test_core_progress_and_elicitation_on_mcp_wire(supports_elicitation: bool) -> None: + schema = {"type": "object", "properties": {"confirmed": {"type": "boolean"}}} + observed: list[tuple[float, float | None, str | None]] = [] + + class Tool: + description = "Report progress and request optional confirmation" + input_schema = _Inputs + output_schema = {"type": "object"} + + async def execute(self, inputs: dict[str, Any], context: Context) -> dict[str, Any]: + await context.report_progress(1, 2, "Preparing") + answer = await context.elicit("Confirm?", schema) + confirmed = answer is not None and answer.action == "accept" and answer.content == {"confirmed": True} + return {"confirmed": confirmed} + + async def elicit(context: Any, request: types.ElicitRequestParams) -> types.ElicitResult: + assert isinstance(request, types.ElicitRequestFormParams) + assert request.message == "Confirm?" + assert request.requestedSchema == schema + return types.ElicitResult(action="accept", content={"confirmed": True}) + + async def progress(count: float, total: float | None, message: str | None) -> None: + observed.append((count, total, message)) + + registry = Registry() + registry.register("test.interaction", Tool()) + router = ExecutionRouter(Executor(registry)) + factory = MCPServerFactory() + server = factory.create_server() + factory.register_handlers(server, factory.build_tools(registry), router) + init = factory.build_init_options(server, "core-interaction", "1") + send_client, read_server = anyio.create_memory_object_stream(10) + send_server, read_client = anyio.create_memory_object_stream(10) + + with anyio.fail_after(5): + async with anyio.create_task_group() as group: + group.start_soon(TransportManager()._run_scoped, server, read_server, send_server, init, "test") + callback = elicit if supports_elicitation else None + async with ClientSession(read_client, send_client, elicitation_callback=callback) as session: + await session.initialize() + result = await session.call_tool("test.interaction", {}, progress_callback=progress) + group.cancel_scope.cancel() + + assert result.isError is False + assert result.structuredContent == {"confirmed": supports_elicitation} + assert observed == [(1, 2, "Preparing")] + + +@pytest.mark.asyncio +async def test_async_bridge_attaches_core_and_legacy_progress() -> None: + class TaskManager: + async def submit(self, module_id: str, arguments: dict[str, Any], context: Context) -> str: + await context.report_progress(1, 2, "core") + await context.data["_mcp_progress"](2, 2, "legacy") + return "task-id" + + received: list[dict[str, Any]] = [] + + async def send(notification: dict[str, Any]) -> None: + received.append(notification) + + bridge = AsyncTaskBridge(TaskManager()) # type: ignore[arg-type] + submitted = await bridge.submit("test.action", {}, Context.create(), progress_token="token", send_notification=send) + assert submitted == {"task_id": "task-id", "status": "pending"} + assert [(notice["params"]["progress"], notice["params"]["message"]) for notice in received] == [ + (1, "core"), + (2, "legacy"), + ] diff --git a/mcp/python/tests/test_artifacts.py b/mcp/python/tests/test_artifacts.py new file mode 100644 index 00000000..c4e63482 --- /dev/null +++ b/mcp/python/tests/test_artifacts.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +import pytest +from apcore import Identity + +from apcore_mcp.artifacts import ARTIFACT_URI_PREFIX, MCPArtifactStore + + +def test_artifact_scope_expiry_and_bounds(monkeypatch): + now = 100.0 + monkeypatch.setattr("apcore_mcp.artifacts.monotonic", lambda: now) + owner = Identity("agent", "agent", scopes=("media.read",), issuer="auth") + narrower = Identity("agent", "agent", scopes=(), issuer="auth") + peer = Identity("peer", "agent", scopes=("media.read",), issuer="auth") + store = MCPArtifactStore(max_bytes=4, max_entries=1, ttl_seconds=10) + + key = store.put(b"PNG", name="result.png", mime_type="image/png", owner=owner) + uri = ARTIFACT_URI_PREFIX + key + assert store.read_uri(uri, owner).content == b"PNG" + assert store.read_uri(uri, narrower) is None + assert store.read_uri(uri, peer) is None + assert store.read_uri(uri, None) is None + assert store.read_uri(uri + "/other", owner) is None + + with pytest.raises(ValueError, match="size"): + store.put(b"large", name="result.png", mime_type="image/png", owner=owner) + with pytest.raises(ValueError, match="full"): + store.put(b"one", name="result.png", mime_type="image/png", owner=owner) + + now = 110.0 + assert store.read_uri(uri, owner) is None + assert store.put(b"new", name="new.png", mime_type="image/png", owner=owner) != key diff --git a/mcp/python/tests/test_review_fixes.py b/mcp/python/tests/test_review_fixes.py index bccd624c..3b9a6e75 100644 --- a/mcp/python/tests/test_review_fixes.py +++ b/mcp/python/tests/test_review_fixes.py @@ -334,6 +334,7 @@ def test_apcore_mcp_build_server_components_passes_output_schema_map(self) -> No mock_executor = MagicMock() mcp = APCoreMCP.__new__(APCoreMCP) + mcp._artifact_store = None mcp._registry = mock_registry mcp._executor = mock_executor mcp._name = "test" diff --git a/mcp/rust/Cargo.lock b/mcp/rust/Cargo.lock index 420548a8..4b63a46f 100644 --- a/mcp/rust/Cargo.lock +++ b/mcp/rust/Cargo.lock @@ -98,9 +98,9 @@ dependencies = [ [[package]] name = "apcore" -version = "1.0.0-alpha.5" +version = "1.0.0-beta.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d19939071ba2c589815c061dfb1ff827862e5f1f52251e88297d49eec500a90" +checksum = "8e7772ee85ac6d1a0538abe1766e6fb192e96a0b657bd05ebf65be60741f47ef" dependencies = [ "async-stream", "async-trait", @@ -131,6 +131,7 @@ dependencies = [ "apcore-toolkit", "async-trait", "axum", + "base64 0.22.1", "chrono", "clap", "futures", diff --git a/mcp/rust/Cargo.toml b/mcp/rust/Cargo.toml index b171ec21..6f9c4313 100644 --- a/mcp/rust/Cargo.toml +++ b/mcp/rust/Cargo.toml @@ -22,12 +22,13 @@ all-features = true rustdoc-args = ["--cfg", "docsrs"] [dependencies] -apcore = { version = "=1.0.0-alpha.5", default-features = false, features = ["config", "sys-modules"] } +apcore = { version = "=1.0.0-beta.1", default-features = false, features = ["config", "sys-modules"] } apcore-toolkit = "=0.15.1-alpha.2" mcp-embedded-ui = "0.5" tokio = { version = "1", features = ["full"] } serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["float_roundtrip"] } +base64 = "0.22" sha2 = "0.10" subtle = "2" # MCP schema validation must reject external retrieval even when apcore enables it. diff --git a/mcp/rust/src/apcore_mcp.rs b/mcp/rust/src/apcore_mcp.rs index f09c34e9..0a58e6a0 100644 --- a/mcp/rust/src/apcore_mcp.rs +++ b/mcp/rust/src/apcore_mcp.rs @@ -441,6 +441,7 @@ pub struct APCoreMCP { /// serve entry points can start its TTL sweep /// ([`ApprovalStore::start_sweep`]). [H-1] approval_store: Option>, + artifact_store: Option>, /// Pre-resolved pipeline execution strategy (from builder/Config Bus). /// Threaded into the executor adapter so trace-path calls honour it. [L-3] resolved_strategy: Option>, @@ -570,7 +571,7 @@ impl APCoreMCP { self.executor.enable_nested_calls(); } - let factory = MCPServerFactory::new(); + let factory = MCPServerFactory::new().with_artifact_store(self.artifact_store.clone()); let mut server = factory .create_server(&self.config.name, &version) .map_err(|e| APCoreMCPError::ServerError(e.to_string()))?; @@ -1426,6 +1427,7 @@ pub struct APCoreMCPBuilder { output_formatter: Option, approval_handler: Option>, approval_store: Option>, + artifact_store: Option>, approval_notify_callback: Option, /// apcore `Middleware` instances to install via `executor.use_middleware()` /// after the backend Executor is resolved. Appended to any middleware @@ -1438,6 +1440,12 @@ pub struct APCoreMCPBuilder { } impl APCoreMCPBuilder { + /// Enable authenticated resource links from this host-owned artifact store. + pub fn artifact_store(mut self, store: Arc) -> Self { + self.artifact_store = Some(store); + self + } + /// Set the backend source (required). pub fn backend(mut self, source: impl Into) -> Self { self.backend = Some(source.into()); @@ -2007,6 +2015,7 @@ impl APCoreMCPBuilder { output_formatter: self.output_formatter, approval_handler, approval_store: retained_store, + artifact_store: self.artifact_store, resolved_strategy, }) } @@ -3789,6 +3798,7 @@ mod tests { approval_handler: None, approval_store: None, resolved_strategy: None, + artifact_store: None, } } @@ -3811,6 +3821,7 @@ mod tests { approval_handler: None, approval_store: None, resolved_strategy: None, + artifact_store: None, } } @@ -3841,6 +3852,7 @@ mod tests { approval_handler: None, approval_store: None, resolved_strategy: None, + artifact_store: None, } } @@ -3867,6 +3879,7 @@ mod tests { approval_handler: None, approval_store: None, resolved_strategy: None, + artifact_store: None, } } @@ -3889,6 +3902,7 @@ mod tests { approval_handler: None, approval_store: None, resolved_strategy: None, + artifact_store: None, } } @@ -4650,6 +4664,7 @@ mod tests { approval_handler: None, approval_store: None, resolved_strategy: None, + artifact_store: None, } } diff --git a/mcp/rust/src/artifact_wire_tests.rs b/mcp/rust/src/artifact_wire_tests.rs new file mode 100644 index 00000000..9461067b --- /dev/null +++ b/mcp/rust/src/artifact_wire_tests.rs @@ -0,0 +1,153 @@ +use std::collections::HashMap; +use std::sync::Arc; + +use apcore::{Context, Identity, Module, ModuleError, Registry}; +use async_trait::async_trait; +use serde_json::{json, Value}; + +use crate::server::{server::ServerHandler, transport::McpHandler}; +use crate::{APCoreMCP, MCPArtifactStore, AUTH_IDENTITY}; + +struct ArtifactModule { + key: String, + sensitive_key: String, +} + +#[async_trait] +impl Module for ArtifactModule { + fn input_schema(&self) -> Value { + json!({"type":"object"}) + } + + fn output_schema(&self) -> Value { + json!({"type":"object","properties": { + "artifact": {"type":"string", "x-mcp-artifact":true}, + "duplicate": {"type":"string", "x-mcp-artifact":true}, + "sensitive": {"type":"string", "x-mcp-artifact":true, "x-sensitive":true}, + "url": {"type":"string", "x-mcp-artifact":true} + }}) + } + + fn description(&self) -> &'static str { + "Return a named artifact" + } + + async fn execute( + &self, + _inputs: Value, + _context: &Context, + ) -> Result { + Ok( + json!({"artifact":self.key,"duplicate":self.key,"sensitive":self.sensitive_key,"url":"https://example.invalid/missing"}), + ) + } +} + +fn owner(roles: Vec) -> Identity { + Identity::new( + "artifact-owner".into(), + "user".into(), + roles, + HashMap::new(), + ) +} + +async fn rpc( + handler: &ServerHandler, + method: &str, + params: Value, + identity: Option, +) -> Value { + AUTH_IDENTITY + .scope( + identity, + handler.handle_message(json!({ + "jsonrpc":"2.0","id":1,"method":method,"params":params + })), + ) + .await + .unwrap() +} + +#[tokio::test] +async fn artifact_links_use_the_live_resource_route_and_preserve_legacy_content() { + let store = Arc::new(MCPArtifactStore::default()); + let caller = owner(vec!["reader".into()]); + let key = store + .put( + vec![0, 255, 1], + "image.bin", + "application/octet-stream", + &caller, + ) + .unwrap(); + let uri = format!("apcore-artifact://{key}"); + let sensitive_key = store + .put(vec![42], "private.bin", "application/octet-stream", &caller) + .unwrap(); + let registry = Arc::new(Registry::new()); + registry + .register_module( + "test.artifact", + Box::new(ArtifactModule { + key: key.clone(), + sensitive_key, + }), + ) + .unwrap(); + let client = APCoreMCP::builder() + .backend(registry) + .artifact_store(store) + .build() + .unwrap(); + let (server, _, tools, options, _, _) = client.build_server_components().unwrap(); + let name = &tools + .iter() + .find(|tool| tool.output_schema.is_some()) + .unwrap() + .name; + let handler = ServerHandler::from_server(&server, options).unwrap(); + let params = json!({"name":name,"arguments":{},"_meta":{"mcpProtocolVersion":"2025-06-18"}}); + let response = rpc(&handler, "tools/call", params.clone(), Some(caller.clone())).await; + let result = &response["result"]; + assert_eq!(result["structuredContent"]["artifact"], key); + assert_eq!(result["content"][0]["type"], "text"); + assert_eq!(result["content"].as_array().unwrap().len(), 2); + assert_eq!( + result["content"][1], + json!({"type":"resource_link","uri":uri,"name":"image.bin","mimeType":"application/octet-stream","size":3}) + ); + + let read = rpc( + &handler, + "resources/read", + json!({"uri":uri}), + Some(caller.clone()), + ) + .await; + assert_eq!( + read["result"]["contents"], + json!([{"uri":uri,"mimeType":"application/octet-stream","blob":"AP8B"}]) + ); + for unauthorized in [None, Some(owner(vec!["writer".into()]))] { + let read = rpc( + &handler, + "resources/read", + json!({"uri":uri}), + unauthorized.clone(), + ) + .await; + assert!(read.get("error").is_some()); + let response = rpc(&handler, "tools/call", params.clone(), unauthorized).await; + assert_eq!(response["result"]["content"].as_array().unwrap().len(), 1); + } + let legacy = rpc( + &handler, + "tools/call", + json!({"name":name,"arguments":{}}), + Some(caller), + ) + .await; + assert!(legacy["result"].get("structuredContent").is_none()); + assert_eq!(legacy["result"]["content"].as_array().unwrap().len(), 1); +} diff --git a/mcp/rust/src/artifacts.rs b/mcp/rust/src/artifacts.rs new file mode 100644 index 00000000..69e696c9 --- /dev/null +++ b/mcp/rust/src/artifacts.rs @@ -0,0 +1,211 @@ +//! Local, authority-bound MCP resource artifacts. + +use std::collections::HashMap; +use std::sync::{Arc, LazyLock, Mutex}; +use std::time::{Duration, Instant}; + +use apcore::Identity; +use regex::Regex; + +pub const ARTIFACT_URI_PREFIX: &str = "apcore-artifact://"; + +#[derive(Debug, thiserror::Error)] +pub enum ArtifactStoreError { + #[error("Artifact limits and expiry must be positive")] + InvalidLimits, + #[error("Artifact content exceeds the size limit")] + TooLarge, + #[error("Artifact name must be a printable filename")] + InvalidName, + #[error("Artifact MIME type is invalid")] + InvalidMediaType, + #[error("An authenticated artifact owner is required")] + MissingOwner, + #[error("Artifact store is full")] + Full, + #[error("Artifact store unavailable")] + Unavailable, +} + +#[derive(PartialEq, Eq)] +struct Authority { + issuer: Option, + identity_type: String, + id: String, + roles: Vec, + key: Option, +} + +impl From<&Identity> for Authority { + fn from(identity: &Identity) -> Self { + let mut roles = identity.roles().to_vec(); + roles.sort_unstable(); + Self { + issuer: identity.issuer().map(str::to_owned), + identity_type: identity.identity_type().to_owned(), + id: identity.id().to_owned(), + roles, + key: identity.authority_key(), + } + } +} + +pub(crate) struct Artifact { + pub(crate) bytes: Vec, + pub(crate) name: String, + pub(crate) mime_type: String, + owner: Authority, + expires_at: Instant, +} + +/// In-memory artifact storage owned by an opt-in MCP application. +pub struct MCPArtifactStore { + max_bytes: usize, + max_entries: usize, + ttl: Duration, + items: Mutex>>, +} + +impl Default for MCPArtifactStore { + fn default() -> Self { + Self { + max_bytes: 8_388_608, + max_entries: 16, + ttl: Duration::from_secs(300), + items: Mutex::default(), + } + } +} + +impl MCPArtifactStore { + /// Create a store with a size limit per artifact, an entry limit and an expiry. + pub fn with_limits( + max_bytes: usize, + max_entries: usize, + ttl: Duration, + ) -> Result { + if max_bytes == 0 + || max_entries == 0 + || ttl.is_zero() + || Instant::now().checked_add(ttl).is_none() + { + return Err(ArtifactStoreError::InvalidLimits); + } + Ok(Self { + max_bytes, + max_entries, + ttl, + items: Mutex::default(), + }) + } + + /// Register owned bytes for a trusted authenticated identity and return an opaque key. + pub fn put( + &self, + bytes: Vec, + name: &str, + mime_type: &str, + owner: &Identity, + ) -> Result { + static FILENAME: LazyLock = LazyLock::new(|| { + Regex::new(r"\A[^\p{C}/\\]{1,200}\z").expect("constant filename pattern") + }); + static MEDIA_TYPE: LazyLock = LazyLock::new(|| { + Regex::new(r"\A[a-zA-Z0-9!#$&^_.+-]+/[a-zA-Z0-9!#$&^_.+-]+\z") + .expect("constant MIME pattern") + }); + if bytes.len() > self.max_bytes { + return Err(ArtifactStoreError::TooLarge); + } + if !FILENAME.is_match(name) { + return Err(ArtifactStoreError::InvalidName); + } + if mime_type.len() > 127 || !MEDIA_TYPE.is_match(mime_type) { + return Err(ArtifactStoreError::InvalidMediaType); + } + if owner.id().is_empty() { + return Err(ArtifactStoreError::MissingOwner); + } + let owner = Authority::from(owner); + let mut items = self + .items + .lock() + .map_err(|_| ArtifactStoreError::Unavailable)?; + let now = Instant::now(); + let expires_at = now + .checked_add(self.ttl) + .ok_or(ArtifactStoreError::InvalidLimits)?; + items.retain(|_, item| item.expires_at > now); + if items.len() >= self.max_entries { + return Err(ArtifactStoreError::Full); + } + let key = uuid::Uuid::new_v4().simple().to_string(); + items.insert( + key.clone(), + Arc::new(Artifact { + bytes, + name: name.to_owned(), + mime_type: mime_type.to_owned(), + owner, + expires_at, + }), + ); + Ok(key) + } + + pub(crate) fn read_uri(&self, uri: &str, identity: Option<&Identity>) -> Option> { + let identity = identity?; + let key = uri.strip_prefix(ARTIFACT_URI_PREFIX)?; + if key.len() != 32 + || !key + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + { + return None; + } + let mut items = self.items.lock().ok()?; + let result = items.get(key)?; + if result.expires_at <= Instant::now() { + items.remove(key); + return None; + } + (result.owner == Authority::from(identity)).then(|| Arc::clone(result)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rejects_external_references_and_reclaims_expired_capacity() { + let owner = Identity::new("owner".into(), "user".into(), vec![], HashMap::new()); + let store = MCPArtifactStore::with_limits(3, 1, Duration::from_secs(1)).unwrap(); + assert!(matches!( + store.put(vec![0; 4], "good", "text/plain", &owner), + Err(ArtifactStoreError::TooLarge) + )); + assert!(matches!( + store.put(vec![0], "../bad", "text/plain", &owner), + Err(ArtifactStoreError::InvalidName) + )); + assert!(matches!( + store.put(vec![0], "good", "text/plain\n", &owner), + Err(ArtifactStoreError::InvalidMediaType) + )); + let key = store.put(vec![0], "good", "text/plain", &owner).unwrap(); + let uri = format!("{ARTIFACT_URI_PREFIX}{key}"); + assert!(store.read_uri("file:///tmp/good", Some(&owner)).is_none()); + assert!(store.read_uri(&uri, None).is_none()); + assert!(store.read_uri(&uri, Some(&owner)).is_some()); + assert!(matches!( + store.put(vec![0], "good", "text/plain", &owner), + Err(ArtifactStoreError::Full) + )); + Arc::get_mut(store.items.lock().unwrap().get_mut(&key).unwrap()) + .unwrap() + .expires_at = Instant::now(); + assert!(store.read_uri(&uri, Some(&owner)).is_none()); + assert!(store.put(vec![0], "good", "text/plain", &owner).is_ok()); + } +} diff --git a/mcp/rust/src/lib.rs b/mcp/rust/src/lib.rs index bf0d4902..2adb61a6 100644 --- a/mcp/rust/src/lib.rs +++ b/mcp/rust/src/lib.rs @@ -15,6 +15,9 @@ pub mod acl_builder; pub mod adapters; pub mod apcore_mcp; pub mod approval_store; +#[cfg(test)] +mod artifact_wire_tests; +mod artifacts; pub mod auth; pub mod cli; pub mod config; @@ -40,6 +43,7 @@ pub use crate::apcore_mcp::{ }; pub use crate::apcore_mcp::{AsyncServeConfig, OpenAIToolsConfig, ServeConfig}; pub use crate::apcore_mcp::{AsyncServeOptions, ExplorerOptions, ServeOptions}; +pub use crate::artifacts::{ArtifactStoreError, MCPArtifactStore, ARTIFACT_URI_PREFIX}; // ---- Re-exports: top-level convenience functions ---------------------------- pub use crate::apcore_mcp::{async_serve, serve, to_openai_tools}; diff --git a/mcp/rust/src/server/factory.rs b/mcp/rust/src/server/factory.rs index 6aee8305..6248da9f 100644 --- a/mcp/rust/src/server/factory.rs +++ b/mcp/rust/src/server/factory.rs @@ -3,23 +3,85 @@ //! Responsible for building tools from registry descriptors, registering //! handlers, and producing a ready-to-run MCPServer. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; +use base64::{engine::general_purpose::STANDARD, Engine as _}; use serde_json::Value; use apcore::module::ModuleAnnotations; use apcore::registry::{ModuleDescriptor, Registry}; use crate::adapters::annotations::{AnnotationMapper, McpAnnotations}; +use crate::artifacts::{MCPArtifactStore, ARTIFACT_URI_PREFIX}; +use crate::auth::middleware::AUTH_IDENTITY; use crate::server::async_task_bridge::AsyncTaskBridge; use crate::server::router::ExecutionRouter; use crate::server::server::{FactoryError, MCPServer, MCPServerConfig}; use crate::server::types::{ - CallToolResult, InitializationOptions, ReadResourceContents, Resource, ResourceTemplate, - ResourcesCapability, ServerCapabilities, TextContent, Tool, ToolAnnotations, ToolsCapability, + CallToolResult, InitializationOptions, ReadResourceContents, Resource, ResourceLink, + ResourceTemplate, ResourcesCapability, ServerCapabilities, TextContent, Tool, ToolAnnotations, + ToolsCapability, }; +fn attach_artifact_links( + store: &MCPArtifactStore, + result: &mut CallToolResult, + schema: Option<&Value>, +) { + if result.is_error { + return; + } + let (Some(values), Some(properties)) = ( + result.structured_content.as_ref(), + schema + .and_then(|schema| schema.get("properties")) + .and_then(Value::as_object), + ) else { + return; + }; + let _ = AUTH_IDENTITY.try_with(|identity| { + let mut emitted = HashSet::new(); + for (name, definition) in properties { + if definition["x-mcp-artifact"] != true || definition["x-sensitive"] == true { + continue; + } + let Some(key) = values[name].as_str().filter(|key| key.len() == 32) else { + continue; + }; + if emitted.contains(key) { + continue; + } + let uri = format!("{ARTIFACT_URI_PREFIX}{key}"); + if let Some(artifact) = store.read_uri(&uri, identity.as_ref()) { + emitted.insert(key); + result.resource_links.push(ResourceLink { + uri, + name: artifact.name.clone(), + mime_type: artifact.mime_type.clone(), + size: artifact.bytes.len(), + }); + } + } + }); +} + +fn read_artifact_resource( + store: &MCPArtifactStore, + uri: String, +) -> Result, FactoryError> { + let artifact = AUTH_IDENTITY + .try_with(|identity| store.read_uri(&uri, identity.as_ref())) + .ok() + .flatten() + .ok_or_else(|| FactoryError::ResourceNotFound("artifact".to_owned()))?; + Ok(vec![ReadResourceContents { + content: STANDARD.encode(&artifact.bytes), + mime_type: artifact.mime_type.clone(), + artifact_uri: Some(uri), + }]) +} + /// Summarize a full apcore `PipelineTrace` JSON into the MCP `_meta.trace` /// shape: `{ step_count, steps: [{ name, duration_ms, skip_reason? }] }`. fn summarize_trace(trace: &Value) -> Value { @@ -348,6 +410,7 @@ async fn call_router_as_resource( Ok(vec![ReadResourceContents { content: text, mime_type: "application/json".to_string(), + artifact_uri: None, }]) } @@ -421,6 +484,7 @@ pub struct MCPServerFactory { /// token. apcore-toolkit 0.6+. Display-overlay /// `mcp.description` overrides are still honoured first. rich_description: bool, + artifact_store: Option>, } impl Default for MCPServerFactory { @@ -435,6 +499,7 @@ impl MCPServerFactory { Self { annotation_mapper: AnnotationMapper, rich_description: false, + artifact_store: None, } } @@ -445,9 +510,15 @@ impl MCPServerFactory { Self { annotation_mapper: AnnotationMapper, rich_description, + artifact_store: None, } } + pub(crate) fn with_artifact_store(mut self, store: Option>) -> Self { + self.artifact_store = store; + self + } + /// Whether this factory renders `Tool.description` as Markdown. pub fn rich_description(&self) -> bool { self.rich_description @@ -865,9 +936,11 @@ impl MCPServerFactory { .collect(); let output_schemas = Arc::new(output_schemas); let router_clone = Arc::clone(&router); + let artifact_store = self.artifact_store.clone(); server.call_tool_handler = Some(Arc::new(move |name, arguments, extra| { let router = Arc::clone(&router_clone); let output_schemas = Arc::clone(&output_schemas); + let artifact_store = artifact_store.clone(); Box::pin(async move { let structured = extra .as_ref() @@ -936,11 +1009,17 @@ impl MCPServerFactory { let result = CallToolResult { structured_content: None, content: text_items, + resource_links: Vec::new(), is_error, meta, }; if structured { - result.with_structured_content(schema.select(output_schemas.get(&name))) + let schema = schema.select(output_schemas.get(&name)); + let mut result = result.with_structured_content(schema); + if let Some(store) = artifact_store.as_deref() { + attach_artifact_links(store, &mut result, schema); + } + result } else { result } @@ -1079,11 +1158,18 @@ impl MCPServerFactory { // read_resource handler let docs_for_read = Arc::clone(&docs); + let artifact_store = self.artifact_store.clone(); server.read_resource_handler = Some(Arc::new(move |uri: String| { let docs = Arc::clone(&docs_for_read); let router = Arc::clone(&router); let available = Arc::clone(&available); + let artifact_store = artifact_store.clone(); Box::pin(async move { + if uri.starts_with(ARTIFACT_URI_PREFIX) { + if let Some(store) = artifact_store.as_deref() { + return read_artifact_resource(store, uri); + } + } if let Some(module_id) = uri.strip_prefix("docs://") { if !docs.contains_key(module_id) { return Err(FactoryError::ResourceNotFound(uri)); @@ -1096,6 +1182,7 @@ impl MCPServerFactory { Some(content) => Ok(vec![ReadResourceContents { content, mime_type: "text/plain".to_string(), + artifact_uri: None, }]), None => Err(FactoryError::ResourceNotFound(uri.clone())), }; diff --git a/mcp/rust/src/server/router.rs b/mcp/rust/src/server/router.rs index bb7904e7..bb55eafc 100644 --- a/mcp/rust/src/server/router.rs +++ b/mcp/rust/src/server/router.rs @@ -230,16 +230,44 @@ pub trait Executor: Send + Sync { /// Everything [`ExecutionRouter::build_context`] produces for one call. /// -/// `.3` is the elicit guard and MUST be bound for the life of the dispatch; +/// `.3` owns the interaction scope for the life of the dispatch; /// see [`ExecutionRouter::build_context`] for why a bare `_` reintroduces the /// bug it exists to prevent. type BuiltContext = ( Value, HashMap>, apcore::Context, - Option, + InteractionGuard, ); +struct InteractionGuard { + native_lifetime: Option, + _legacy_elicitation: Option, +} + +impl Drop for InteractionGuard { + fn drop(&mut self) { + if let Some(lifetime) = &self.native_lifetime { + lifetime.cancel(); + } + } +} + +// Use the Core callback contract's ModuleError directly. +#[allow(clippy::result_large_err)] +async fn during_interaction( + lifetime: &CancelToken, + operation: impl Future>, +) -> Result { + tokio::select! { + biased; + () = lifetime.cancelled() => Err(apcore::ExecutionCancelledError::without_module( + "The MCP tool call has completed", + ).into()), + result = operation => result, + } +} + /// Build the per-call [`ElicitCallback`] that forwards to the MCP session. /// /// Extracted because the callback is needed twice per call — once for the @@ -262,6 +290,44 @@ fn make_elicit_callback(session: Arc) -> crate::helpers::Elic }) } +fn native_elicitation_handler( + session: Arc, + lifetime: CancelToken, +) -> apcore::ElicitationHandler { + use crate::helpers::ElicitAction; + use apcore::{ElicitationResult, ErrorCode, ModuleError}; + + Arc::new(move |request| { + let session = Arc::clone(&session); + let lifetime = lifetime.clone(); + Box::pin(async move { + let schema = request.requested_schema.unwrap_or_else(|| json!({})); + let reply = during_interaction(&lifetime, async { + session + .elicit_form(&request.message, &schema) + .await + .map_err(|_| { + ModuleError::new(ErrorCode::GeneralInternalError, "MCP elicitation failed") + }) + }) + .await?; + match reply.action { + ElicitAction::Accept => match reply.content { + Some(Value::Object(content)) => Ok(ElicitationResult::Accept { content }), + _ => Err(ModuleError::invalid_input( + "MCP elicitation accepted without object content", + )), + }, + ElicitAction::Decline => Ok(ElicitationResult::Decline), + ElicitAction::Cancel => Ok(ElicitationResult::Cancel), + ElicitAction::Unknown(_) => Err(ModuleError::invalid_input( + "MCP elicitation returned an unknown action", + )), + } + }) + }) +} + /// Maximum recursion depth for [`deep_merge`]. const DEEP_MERGE_MAX_DEPTH: usize = 32; @@ -373,6 +439,11 @@ pub type SendNotificationFn = Arc< /// Handle to the MCP session for elicitation requests. #[async_trait] pub trait SessionHandle: Send + Sync { + /// Whether this session can present an elicitation form. + fn supports_elicitation(&self) -> bool { + true + } + /// Send an elicitation form to the client and return the result. async fn elicit_form( &self, @@ -1264,10 +1335,10 @@ impl ExecutionRouter { identity, typed_identity: None, }; - // `_elicit_guard` keeps the registered elicit callback alive for the + // `_interaction_guard` keeps callbacks available for the // whole dispatch below. Binding it to a bare `_` would drop it here and // deregister the callback before the approval gate ever runs. - let (context_value, _context_data, apcore_ctx, _elicit_guard) = + let (context_value, _context_data, apcore_ctx, _interaction_guard) = Self::build_context_with_trace(&call_extra, trace_parent.clone(), Some(cancel_token)); // Short-circuit the `__apcore_approval_check` meta-tool via the @@ -1554,7 +1625,8 @@ impl ExecutionRouter { }); // Build per-call context - let (context_value, _context_data, apcore_ctx, _elicit_guard) = Self::build_context(&extra); + let (context_value, _context_data, apcore_ctx, _interaction_guard) = + Self::build_context(&extra); // Pre-execution validation. catch_unwind guards against panics from // third-party executor implementations (symmetric with validate_tool's @@ -1684,18 +1756,18 @@ impl ExecutionRouter { /// callback objects) and in `apcore_ctx.data` (as marker values so /// modules can detect availability). /// - /// Returns `(context_value, context_data, apcore_context, elicit_guard)` + /// Returns `(context_value, context_data, apcore_context, interaction_guard)` /// where `context_data` holds the callback objects that cannot be /// serialized into JSON, and `apcore_context` is the proper apcore /// `Context`. /// /// # The elicit guard MUST outlive the call /// - /// `elicit_guard` owns the registry entry that + /// `interaction_guard` owns the registry entry that /// [`MCP_ELICIT_CALL_ID_KEY`] in `apcore_context.data` points at. Dropping /// it deregisters the callback, so an approval handler running after that /// point resolves the id to nothing and rejects. Bind it for the whole - /// dispatch (`let (.., _elicit_guard) = ...`) — never to a bare `_`, which + /// dispatch (`let (.., _interaction_guard) = ...`) — never to a bare `_`, which /// drops immediately and reinstates exactly the bug this returns it to /// prevent. fn build_context(extra: &CallExtra) -> BuiltContext { @@ -1767,15 +1839,25 @@ impl ExecutionRouter { let has_progress = extra.progress_token.is_some() && extra.send_notification.is_some(); let has_elicit = extra.session.is_some(); + let native_session = extra + .session + .as_ref() + .filter(|session| session.supports_elicitation()); + let lifetime = (has_progress || native_session.is_some()).then(CancelToken::new); // Inject progress callback - if let (Some(ref token), Some(ref send_notification)) = - (&extra.progress_token, &extra.send_notification) - { + if let (Some(token), Some(send_notification), Some(lifetime)) = ( + &extra.progress_token, + &extra.send_notification, + lifetime.as_ref(), + ) { let token = token.clone(); let sn = Arc::clone(send_notification); - let progress_cb: crate::helpers::ProgressCallback = - Box::new(move |progress, total, message| { + let progress_cb = Arc::new( + move |progress: f64, + total: Option, + message: Option| + -> Pin + Send>> { let token_val = progress_token_to_value(&token); let sn = Arc::clone(&sn); Box::pin(async move { @@ -1799,14 +1881,30 @@ impl ExecutionRouter { tracing::debug!("Failed to send progress notification: {e}"); } }) - }); - data.insert(MCP_PROGRESS_KEY.to_string(), Box::new(progress_cb)); + }, + ); + let legacy = Arc::clone(&progress_cb); + let legacy_callback: crate::helpers::ProgressCallback = + Box::new(move |progress, total, message| legacy(progress, total, message)); + data.insert(MCP_PROGRESS_KEY.to_string(), Box::new(legacy_callback)); + let lifetime = lifetime.clone(); + apcore_ctx = apcore_ctx.with_progress_reporter(Some(Arc::new(move |update| { + let callback = Arc::clone(&progress_cb); + let lifetime = lifetime.clone(); + Box::pin(async move { + during_interaction(&lifetime, async move { + callback(update.progress, update.total, update.message).await; + Ok(()) + }) + .await + }) + }))); } // Inject elicit callback. // - // Two copies, because they serve two different consumers. The - // side-channel `data` map is the historical home and is typed + // The legacy callbacks serve two consumers. The side-channel + // `data` map is the historical home and is typed // `Box`, which no apcore surface can read. The registry copy // is the one an `ApprovalHandler` can actually reach: it is addressed // by the id written into `apcore_ctx.data` below, and the returned @@ -1821,11 +1919,15 @@ impl ExecutionRouter { make_elicit_callback(Arc::clone(session)), )); } + if let (Some(session), Some(lifetime)) = (native_session, lifetime.as_ref()) { + apcore_ctx = apcore_ctx.with_elicitation_handler(Some(native_elicitation_handler( + Arc::clone(session), + lifetime.clone(), + ))); + } - // Write marker values into apcore Context.data so modules can - // detect callback availability. Actual callbacks live in the - // side-channel `data` map since serde_json::Value cannot hold - // function pointers. + // Retain the legacy availability markers and approval handle. + // Native callbacks live in the Context's local attachments. { let mut shared = apcore_ctx.data.write(); if has_progress { @@ -1863,7 +1965,15 @@ impl ExecutionRouter { Value::String(apcore_ctx.trace_id.clone()), ); - (Value::Object(context_obj), data, apcore_ctx, elicit_guard) + ( + Value::Object(context_obj), + data, + apcore_ctx, + InteractionGuard { + native_lifetime: lifetime, + _legacy_elicitation: elicit_guard, + }, + ) } // ----------------------------------------------------------------------- diff --git a/mcp/rust/src/server/server.rs b/mcp/rust/src/server/server.rs index ed1d6967..093446f3 100644 --- a/mcp/rust/src/server/server.rs +++ b/mcp/rust/src/server/server.rs @@ -890,8 +890,9 @@ impl crate::server::transport::McpHandler for ServerHandler { let mut call_result = (self.call_tool)(name, arguments, extra).await; if !self.supports_structured_results(&message) { call_result.structured_content = None; + call_result.resource_links.clear(); } - RpcResult::Success(serde_json::to_value(call_result).unwrap_or_default()) + RpcResult::Success(call_result.to_wire()) } "resources/list" => { if let Some(ref handler) = self.list_resources { @@ -936,15 +937,8 @@ impl crate::server::transport::McpHandler for ServerHandler { if let Some(ref handler) = self.read_resource { match handler(uri).await { Ok(contents) => { - let contents_json: Vec = contents - .iter() - .map(|c| { - serde_json::json!({ - "content": c.content, - "mimeType": c.mime_type - }) - }) - .collect(); + let contents_json: Vec = + contents.iter().map(ReadResourceContents::to_wire).collect(); RpcResult::Success(serde_json::json!({ "contents": contents_json })) } Err(e) => ServerHandler::rpc_error(-32602, e.to_string()), diff --git a/mcp/rust/src/server/session.rs b/mcp/rust/src/server/session.rs index 80873877..6c5e9dc2 100644 --- a/mcp/rust/src/server/session.rs +++ b/mcp/rust/src/server/session.rs @@ -249,6 +249,10 @@ impl McpSession { #[async_trait] impl SessionHandle for McpSession { + fn supports_elicitation(&self) -> bool { + McpSession::supports_elicitation(self) + } + async fn elicit_form( &self, message: &str, diff --git a/mcp/rust/src/server/transport.rs b/mcp/rust/src/server/transport.rs index 502d4aa6..bd0a9256 100644 --- a/mcp/rust/src/server/transport.rs +++ b/mcp/rust/src/server/transport.rs @@ -2420,6 +2420,14 @@ mod tests { /// Collect the next `count` JSON-RPC responses carried by `message` events. async fn collect_sse_responses(body: &mut axum::body::Body, count: usize) -> Vec { + collect_sse_messages(body, count, |message| message.get("id").is_some()).await + } + + async fn collect_sse_messages( + body: &mut axum::body::Body, + count: usize, + accept: impl Fn(&Value) -> bool, + ) -> Vec { let mut responses = Vec::new(); while responses.len() < count { let chunk = read_sse_chunk(body).await; @@ -2430,7 +2438,7 @@ mod tests { let Ok(value) = serde_json::from_str::(payload.trim()) else { continue; }; - if value.get("id").is_some() { + if accept(&value) { responses.push(value); } } @@ -4361,6 +4369,262 @@ mod tests { .expect("the stdio loop must exit cleanly on EOF"); } + type RetainedContext = Arc>>>; + + struct NativeInteraction(RetainedContext); + + #[async_trait::async_trait] + impl apcore::Module for NativeInteraction { + fn input_schema(&self) -> Value { + serde_json::json!({"type":"object"}) + } + + fn output_schema(&self) -> Value { + serde_json::json!({"type":"object"}) + } + + fn description(&self) -> &'static str { + "Use the Core Context interaction methods" + } + + async fn execute( + &self, + _inputs: Value, + context: &apcore::Context, + ) -> Result { + context + .report_progress(2.0, Some(3.0), Some("native progress")) + .await?; + let reply = context + .elicit("Native prompt?", serde_json::json!({"type":"object"})) + .await?; + *self.0.lock().unwrap() = Some(context.clone()); + Ok(serde_json::json!({"reply":reply})) + } + } + + fn native_interaction_handler() -> ( + Arc, + String, + RetainedContext, + ) { + let retained = RetainedContext::default(); + let registry = Arc::new(apcore::Registry::new()); + registry + .register_module( + "demo.native", + Box::new(NativeInteraction(Arc::clone(&retained))), + ) + .unwrap(); + let bridge = crate::APCoreMCP::builder() + .backend(registry) + .build() + .unwrap(); + let (server, _, tools, options, _, _) = bridge.build_server_components().unwrap(); + let handler = crate::server::server::ServerHandler::from_server(&server, options).unwrap(); + (Arc::new(handler), tools[0].name.clone(), retained) + } + + fn native_init(capabilities: Value) -> Value { + serde_json::json!({ + "jsonrpc":"2.0","id":1,"method":"initialize", + "params":{"protocolVersion":"2025-06-18","capabilities":capabilities} + }) + } + + fn native_call(tool_name: &str, id: u64) -> Value { + serde_json::json!({ + "jsonrpc":"2.0","id":id,"method":"tools/call", + "params":{"name":tool_name,"arguments":{},"_meta":{"progressToken":"native"}} + }) + } + + fn native_prompt(progress: &Value, prompt: &Value) { + assert_eq!(progress["method"], "notifications/progress"); + assert_eq!(progress["params"]["progressToken"], "native"); + assert_eq!(progress["params"]["progress"], 2.0); + assert_eq!(progress["params"]["message"], "native progress"); + assert_eq!(prompt["method"], "elicitation/create"); + assert_eq!(prompt["params"]["message"], "Native prompt?"); + assert_eq!( + prompt["params"]["requestedSchema"], + serde_json::json!({"type":"object"}) + ); + } + + fn native_result(response: &Value) -> Value { + assert_eq!(response["id"], 2); + assert_eq!(response["result"]["isError"], false); + serde_json::from_str(response["result"]["content"][0]["text"].as_str().unwrap()).unwrap() + } + + #[tokio::test] + async fn stdio_delivers_native_context_progress_and_elicitation() { + let (handler, name, retained) = native_interaction_handler(); + let tm = TransportManager::new(None); + let (client, server) = tokio::io::duplex(64 * 1024); + let (client_read, mut client_write) = tokio::io::split(client); + let mut client_lines = BufReader::new(client_read).lines(); + let serve = tokio::spawn(async move { + let (server_read, server_write) = tokio::io::split(server); + tm.run_stdio_with_io(server_read, server_write, handler.as_ref()) + .await + }); + send( + &mut client_write, + native_init(serde_json::json!({"elicitation":{}})), + ) + .await; + assert_eq!(recv(&mut client_lines).await["id"], 1); + send(&mut client_write, native_call(&name, 2)).await; + let progress = recv(&mut client_lines).await; + assert_eq!(progress["method"], "notifications/progress"); + let prompt = recv(&mut client_lines).await; + native_prompt(&progress, &prompt); + send( + &mut client_write, + serde_json::json!({ + "jsonrpc":"2.0","id":prompt["id"], + "result":{"action":"accept","content":{"confirmed":true}} + }), + ) + .await; + let output = native_result(&recv(&mut client_lines).await); + assert_eq!( + output["reply"], + serde_json::json!({"action":"accept","content":{"confirmed":true}}) + ); + let stale = retained.lock().unwrap().take().unwrap(); + let late_progress = stale + .report_progress(1.0, None, Some("late")) + .await + .unwrap_err(); + assert_eq!(late_progress.code, apcore::ErrorCode::ExecutionCancelled); + let late_elicit = tokio::time::timeout( + std::time::Duration::from_millis(500), + stale.elicit("Late prompt", None), + ) + .await + .unwrap() + .unwrap_err(); + assert_eq!(late_elicit.code, apcore::ErrorCode::ExecutionCancelled); + send(&mut client_write, native_call(&name, 3)).await; + let progress = recv(&mut client_lines).await; + let prompt = recv(&mut client_lines).await; + native_prompt(&progress, &prompt); + send(&mut client_write, cancel_request(3.into())).await; + send( + &mut client_write, + serde_json::json!({ + "jsonrpc":"2.0","id":4,"method":"tools/list","params":{} + }), + ) + .await; + // The transport suppresses cancelled responses. The next request + // still receives its response while the client ignores the old prompt. + let next = recv(&mut client_lines).await; + assert_eq!(next["id"], 4); + assert!(next["result"]["tools"].is_array()); + drop(client_write); + drop(client_lines); + serve.await.unwrap().unwrap(); + } + + #[tokio::test] + async fn sse_delivers_native_context_interactions_on_the_calling_session() { + let (handler, name, _) = native_interaction_handler(); + let (app, _) = sse_test_app_parts_with(Arc::new(TransportManager::new(None)), handler); + let (mut body, id) = open_sse_session(&app).await; + assert_eq!( + post_sse_raw( + &app, + &id, + native_init(serde_json::json!({"elicitation":{}})) + ) + .await, + StatusCode::ACCEPTED + ); + assert_eq!(collect_sse_responses(&mut body, 1).await[0]["id"], 1); + assert_eq!( + post_sse_raw(&app, &id, native_call(&name, 2)).await, + StatusCode::ACCEPTED + ); + let messages = collect_sse_messages(&mut body, 2, |_| true).await; + native_prompt(&messages[0], &messages[1]); + assert_eq!( + post_sse_raw( + &app, + &id, + serde_json::json!({ + "jsonrpc":"2.0","id":messages[1]["id"],"result":{"action":"decline"} + }) + ) + .await, + StatusCode::ACCEPTED + ); + let result = collect_sse_responses(&mut body, 1).await; + assert_eq!( + native_result(&result[0])["reply"], + serde_json::json!({"action":"decline"}) + ); + } + + #[tokio::test] + async fn stdio_without_elicitation_capability_gets_no_native_prompt() { + let (handler, name, _) = native_interaction_handler(); + let tm = TransportManager::new(None); + let (client, server) = tokio::io::duplex(64 * 1024); + let (client_read, mut client_write) = tokio::io::split(client); + let mut client_lines = BufReader::new(client_read).lines(); + let serve = tokio::spawn(async move { + let (server_read, server_write) = tokio::io::split(server); + tm.run_stdio_with_io(server_read, server_write, handler.as_ref()) + .await + }); + send(&mut client_write, native_init(serde_json::json!({}))).await; + assert_eq!(recv(&mut client_lines).await["id"], 1); + send(&mut client_write, native_call(&name, 2)).await; + assert_eq!( + recv(&mut client_lines).await["method"], + "notifications/progress" + ); + assert!(native_result(&recv(&mut client_lines).await)["reply"].is_null()); + drop(client_write); + drop(client_lines); + serve.await.unwrap().unwrap(); + } + + #[tokio::test] + async fn streamable_http_does_not_offer_native_callbacks_on_the_shared_session() { + use axum::{body::Body, http::Request}; + use http_body_util::BodyExt; + use tower::ServiceExt; + + let (handler, name, _) = native_interaction_handler(); + let sessions = handler.session_registry().unwrap(); + let tm = Arc::new(TransportManager::new(None)); + let app = tm.build_streamable_http_app(handler, None); + let post = |message: Value| { + let app = app.clone(); + async move { + let request = Request::post("/mcp") + .header("content-type", "application/json") + .body(Body::from(message.to_string())) + .unwrap(); + let response = app.oneshot(request).await.unwrap(); + let body = response.into_body().collect().await.unwrap().to_bytes(); + serde_json::from_slice::(&body).unwrap() + } + }; + assert_eq!( + post(native_init(serde_json::json!({"elicitation":{}}))).await["id"], + 1 + ); + let result = post(native_call(&name, 2)).await; + assert!(native_result(&result)["reply"].is_null()); + assert!(sessions.is_empty()); + } + #[tokio::test] async fn stdio_does_not_prompt_a_client_that_never_declared_elicitation() { // The control for the test above. If capability gating were dropped, diff --git a/mcp/rust/src/server/types.rs b/mcp/rust/src/server/types.rs index d4d773d1..7affda77 100644 --- a/mcp/rust/src/server/types.rs +++ b/mcp/rust/src/server/types.rs @@ -85,6 +85,9 @@ fn matches_output_schema(value: &Value, schema: &Value) -> bool { #[serde(rename_all = "camelCase")] pub struct CallToolResult { pub content: Vec, + /// Additional resource links for the MCP wire result. + #[serde(skip)] + pub resource_links: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub structured_content: Option, pub is_error: bool, @@ -129,11 +132,41 @@ impl CallToolResult { pub fn new(content: Vec, is_error: bool) -> Self { Self { content, + resource_links: Vec::new(), structured_content: None, is_error, meta: None, } } + + pub(crate) fn to_wire(&self) -> Value { + let mut value = serde_json::to_value(self).unwrap_or_default(); + if let Some(content) = value.get_mut("content").and_then(Value::as_array_mut) { + content.extend(self.resource_links.iter().map(ResourceLink::to_wire)); + } + value + } +} + +/// A readable artifact link carried alongside a normal tool result. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ResourceLink { + pub uri: String, + pub name: String, + pub mime_type: String, + pub size: usize, +} + +impl ResourceLink { + fn to_wire(&self) -> Value { + serde_json::json!({ + "type": "resource_link", + "uri": self.uri, + "name": self.name, + "mimeType": self.mime_type, + "size": self.size, + }) + } } /// An MCP Resource definition exposed via `list_resources`. @@ -151,6 +184,20 @@ pub struct Resource { pub struct ReadResourceContents { pub content: String, pub mime_type: String, + /// For an artifact, content is the encoded blob at this URI. + #[serde(skip)] + pub artifact_uri: Option, +} + +impl ReadResourceContents { + pub(crate) fn to_wire(&self) -> Value { + match &self.artifact_uri { + Some(uri) => { + serde_json::json!({"uri":uri,"blob":self.content,"mimeType":self.mime_type}) + } + None => serde_json::json!({"content":self.content,"mimeType":self.mime_type}), + } + } } /// An MCP Resource Template definition exposed via `resources/templates/ @@ -596,6 +643,7 @@ mod tests { #[test] fn test_call_tool_result_serialization() { let result = CallToolResult { + resource_links: Vec::new(), structured_content: None, content: vec![TextContent::new("result text")], is_error: false, @@ -612,6 +660,7 @@ mod tests { #[test] fn test_read_resource_contents_serialization() { let contents = ReadResourceContents { + artifact_uri: None, content: "# Documentation".to_string(), mime_type: "text/plain".to_string(), }; diff --git a/mcp/typescript/src/apcore-mcp.ts b/mcp/typescript/src/apcore-mcp.ts index fec0ff05..9eb3108a 100644 --- a/mcp/typescript/src/apcore-mcp.ts +++ b/mcp/typescript/src/apcore-mcp.ts @@ -35,6 +35,7 @@ import type { import type { Authenticator } from "./auth/types.js"; import type { MetricsExporter } from "./server/transport.js"; import type { ObservabilityFlag } from "./server/observability.js"; +import type { MCPArtifactStore } from "./artifacts.js"; import type { ApprovalStore } from "./approval-store.js"; import { withStdioOutput } from "./server/stdio-output.js"; import { @@ -85,6 +86,7 @@ export interface APCoreMCPOptions { * approval handler. */ approvalStore?: ApprovalStore; + artifactStore?: MCPArtifactStore; /** * Optional callback invoked when a new approval is requested. * Used together with `approvalStore` to fan out to Slack/email/webhooks. @@ -288,6 +290,7 @@ export class APCoreMCP { exemptPaths: this._options.exemptPaths, approvalHandler: this._options.approvalHandler, approvalStore: this._options.approvalStore, + artifactStore: this._options.artifactStore, approvalNotify: this._options.approvalNotify, outputFormatter: this._options.outputFormatter, middleware: this._options.middleware, @@ -382,6 +385,7 @@ export class APCoreMCP { exemptPaths: this._options.exemptPaths, approvalHandler: this._options.approvalHandler, approvalStore: this._options.approvalStore, + artifactStore: this._options.artifactStore, approvalNotify: this._options.approvalNotify, endpoint: options.endpoint, outputFormatter: this._options.outputFormatter, diff --git a/mcp/typescript/src/artifacts.ts b/mcp/typescript/src/artifacts.ts new file mode 100644 index 00000000..6c17edf8 --- /dev/null +++ b/mcp/typescript/src/artifacts.ts @@ -0,0 +1,98 @@ +import { randomUUID } from "node:crypto"; +import type { Identity } from "apcore-js"; + +export const ARTIFACT_URI_PREFIX = "apcore-artifact://"; +const artifactIdPattern = /^[a-f0-9]{32}$/; +const mediaTypePattern = /^[a-zA-Z0-9!#$&^_.+-]+\/[a-zA-Z0-9!#$&^_.+-]+(?![\s\S])/; + +type ArtifactMetadata = { readonly name: string; readonly mimeType: string; readonly size: number }; +type StoredArtifact = ArtifactMetadata & { + readonly content: Buffer; + readonly authority: string; + readonly expiresAt: number; +}; + +function authority(identity: Identity): string { + return JSON.stringify([identity.issuer ?? null, identity.type, identity.id, + Array.from(identity.roles).sort(), identity.authorityKey?.() ?? null]); +} + +/** Bounded in-process media storage owned by the embedding MCP host. */ +export class MCPArtifactStore { + private readonly maxBytes: number; + private readonly maxEntries: number; + private readonly ttlMilliseconds: number; + private readonly items = new Map(); + + constructor({ maxBytes = 8_388_608, maxEntries = 16, ttlSeconds = 300 } = {}) { + if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) { + throw new TypeError("Artifact size limit must be a positive integer"); + } + if (!Number.isSafeInteger(maxEntries) || maxEntries < 1) { + throw new TypeError("Artifact entry limit must be a positive integer"); + } + if (!Number.isFinite(ttlSeconds * 1000) || ttlSeconds <= 0) { + throw new TypeError("Artifact expiry must be positive and finite"); + } + this.maxBytes = maxBytes; + this.maxEntries = maxEntries; + this.ttlMilliseconds = ttlSeconds * 1000; + } + + put( + content: Uint8Array, + { name, mimeType, owner }: { name: string; mimeType: string; owner: Identity }, + ): string { + if (!(content instanceof Uint8Array) || content.length > this.maxBytes) { + throw new TypeError("Artifact content must be bytes within the size limit"); + } + if (name.length === 0 || Array.from(name).length > 200 || + name.includes("/") || name.includes(String.fromCharCode(92)) || /\p{C}/u.test(name)) { + throw new TypeError("Artifact name must be a printable filename"); + } + if (mimeType.length > 127 || !mediaTypePattern.test(mimeType)) { + throw new TypeError("Artifact MIME type is invalid"); + } + if (!owner.id) throw new TypeError("An authenticated artifact owner is required"); + + const now = performance.now(); + for (const [key, item] of this.items) { + if (item.expiresAt <= now) this.items.delete(key); + } + if (this.items.size >= this.maxEntries) throw new Error("Artifact store is full"); + + const key = randomUUID().replaceAll("-", ""); + this.items.set(key, { + content: Buffer.from(content), name, mimeType, size: content.length, + authority: authority(owner), expiresAt: now + this.ttlMilliseconds, + }); + return key; + } + + describe(uri: string, identity: Identity | null): ArtifactMetadata | null { + const artifact = this.find(uri, identity); + return artifact === null ? null : { + name: artifact.name, mimeType: artifact.mimeType, size: artifact.size, + }; + } + + read(uri: string, identity: Identity | null): { blob: string; mimeType: string } | null { + const artifact = this.find(uri, identity); + return artifact === null ? null : { + blob: artifact.content.toString("base64"), mimeType: artifact.mimeType, + }; + } + + private find(uri: string, identity: Identity | null): StoredArtifact | null { + if (identity === null || !uri.startsWith(ARTIFACT_URI_PREFIX)) return null; + const key = uri.slice(ARTIFACT_URI_PREFIX.length); + if (key.length !== 32 || !artifactIdPattern.test(key)) return null; + const artifact = this.items.get(key); + if (!artifact) return null; + if (artifact.expiresAt <= performance.now()) { + this.items.delete(key); + return null; + } + return artifact.authority === authority(identity) ? artifact : null; + } +} diff --git a/mcp/typescript/src/helpers.ts b/mcp/typescript/src/helpers.ts index 158a0a13..727af601 100644 --- a/mcp/typescript/src/helpers.ts +++ b/mcp/typescript/src/helpers.ts @@ -70,3 +70,32 @@ export async function elicit( } return null; } + +type CoreElicitationReply = + | { action: "accept"; content: Record } + | { action: "decline" | "cancel" }; + +interface InteractionBindings { + withProgressReporter?(reporter: (progress: number, total?: number, message?: string) => Promise): T & InteractionBindings; + withElicitationHandler?(handler: (message: string, schema?: Record) => Promise): T & InteractionBindings; +} + +/** @internal Install Core's interaction slots when present through the same detachable callback data. */ +export function withCoreInteractions(context: T): T { + const legacy = { data: context.data }; + let bound = context as T & InteractionBindings; + if (typeof bound.withProgressReporter === "function" && typeof legacy.data[MCP_PROGRESS_KEY] === "function") { + bound = bound.withProgressReporter((progress, total, message) => reportProgress(legacy, progress, total, message)); + } + if (typeof bound.withElicitationHandler === "function" && typeof legacy.data[MCP_ELICIT_KEY] === "function") { + bound = bound.withElicitationHandler(async (message, schema) => { + const result = await elicit(legacy, message, schema); + // A detached session can no longer interact. Native Core represents it as a cancelled request. + if (result === null || result.action === "cancel") return { action: "cancel" }; + if (result.action === "decline") return { action: "decline" }; + if (result.action === "accept" && result.content !== undefined) return { action: "accept", content: result.content }; + throw new Error("MCP elicitation did not return accepted content"); + }); + } + return bound; +} diff --git a/mcp/typescript/src/index.ts b/mcp/typescript/src/index.ts index b8e26f89..6e2435ee 100644 --- a/mcp/typescript/src/index.ts +++ b/mcp/typescript/src/index.ts @@ -8,6 +8,7 @@ */ import { createNodeHandler, type Tool as UITool } from "mcp-embedded-ui"; +import type { MCPArtifactStore } from "./artifacts.js"; import { OpenAIConverter } from "./converters/openai.js"; import type { ConvertRegistryOptions } from "./converters/openai.js"; import { MCPServerFactory } from "./server/factory.js"; @@ -36,6 +37,8 @@ import { StorageBackedApprovalHandler } from "./adapters/approval.js"; import { ApprovalBridge } from "./server/approval-bridge.js"; import pkg from "../package.json" with { type: "json" }; +export { MCPArtifactStore } from "./artifacts.js"; + export const VERSION: string = pkg.version; // ─── Type Exports ──────────────────────────────────────────────────────────── @@ -662,6 +665,7 @@ export interface BaseServeOptions { * stopped on shutdown), preventing unbounded record growth. */ approvalStore?: ApprovalStore; + artifactStore?: MCPArtifactStore; /** * Optional callback invoked when a new approval is requested. Used together * with `approvalStore` to fan out to Slack/email/webhooks. @@ -954,7 +958,7 @@ async function serveInternal( : null; // Build MCP server components - const factory = new MCPServerFactory(); + const factory = new MCPServerFactory({ artifactStore: options.artifactStore }); // aiperceivable/apcore-mcp#16 phase A: advertise `com.aiperceivable/management` // in `initialize` capabilities only for surfaces actually registered. const managementSurfaces = computeManagementSurfaces(registry); @@ -1303,7 +1307,7 @@ export async function asyncServe( : null; // Build MCP server components - const factory = new MCPServerFactory(); + const factory = new MCPServerFactory({ artifactStore: options.artifactStore }); // aiperceivable/apcore-mcp#16 phase A: advertise `com.aiperceivable/management` // in `initialize` capabilities only for surfaces actually registered. const managementSurfaces = computeManagementSurfaces(registry); diff --git a/mcp/typescript/src/server/async-task-bridge.ts b/mcp/typescript/src/server/async-task-bridge.ts index dee51f54..c0506aa1 100644 --- a/mcp/typescript/src/server/async-task-bridge.ts +++ b/mcp/typescript/src/server/async-task-bridge.ts @@ -14,7 +14,7 @@ import { InvalidInputError } from "apcore-js"; import { markBackgroundApprovalContext } from "../approval-reply.js"; -import { MCP_ELICIT_KEY, MCP_PROGRESS_KEY } from "../helpers.js"; +import { MCP_ELICIT_KEY, MCP_PROGRESS_KEY, withCoreInteractions } from "../helpers.js"; import type { ModuleDescriptor } from "../types.js"; import { ErrorCodes } from "../types.js"; @@ -366,11 +366,12 @@ export class AsyncTaskBridge { if (contextData && typeof contextData === "object") { (contextData as Record)[MCP_PROGRESS_KEY] = async ( progress: number, - total: number, + total?: number, + message?: string, ) => { await sendNotification({ method: "notifications/progress", - params: { progressToken, progress, total }, + params: { progressToken, progress, total: total ?? 0, ...(message !== undefined ? { message } : {}) }, }); }; } @@ -380,17 +381,19 @@ export class AsyncTaskBridge { // The marker carries no approval state or credentials. const callbackSessionKey = options?.callbackSessionKey ?? options?.sessionKey; let detach: (() => void) | undefined; + let invocationContext = context; if (context && typeof context === "object" && "data" in context && context.data && typeof context.data === "object") { - markBackgroundApprovalContext(context.data); + const data = context.data as Record; + markBackgroundApprovalContext(data); if (callbackSessionKey !== undefined) { - const data = context.data as Record; const detachProgress = makeDetachableCallback(data, MCP_PROGRESS_KEY, undefined); const detachElicit = makeDetachableCallback(data, MCP_ELICIT_KEY, null); if (detachProgress || detachElicit) detach = () => { detachProgress?.(); detachElicit?.(); }; } + invocationContext = withCoreInteractions(context as { data: Record }); } - const taskId = await this._submitOwnedTask(moduleId, inputs, context ?? null, owner); + const taskId = await this._submitOwnedTask(moduleId, inputs, invocationContext ?? null, owner); if (options?.progressToken !== undefined || detach) { this._taskNotifications.set(taskId, { progressToken: options?.progressToken, detach, sessionKey: callbackSessionKey }); } diff --git a/mcp/typescript/src/server/factory.ts b/mcp/typescript/src/server/factory.ts index a70c2fd1..25432c32 100644 --- a/mcp/typescript/src/server/factory.ts +++ b/mcp/typescript/src/server/factory.ts @@ -27,6 +27,8 @@ import type { ReadResourceResult, } from "@modelcontextprotocol/sdk/types.js"; +import { ARTIFACT_URI_PREFIX, type MCPArtifactStore } from "../artifacts.js"; +import { getCurrentIdentity } from "../auth/storage.js"; import { AnnotationMapper } from "../adapters/annotations.js"; import type { Registry, ModuleDescriptor, JsonSchema } from "../types.js"; import type { ExecutionRouter } from "./router.js"; @@ -103,6 +105,7 @@ export interface MCPServerFactoryOptions { * one-time warning. */ richDescription?: boolean; + artifactStore?: MCPArtifactStore; } function outputSchemaForTool(descriptor: ModuleDescriptor): Tool["outputSchema"] { @@ -114,6 +117,7 @@ function outputSchemaForTool(descriptor: ModuleDescriptor): Tool["outputSchema"] export class MCPServerFactory { private readonly _annotationMapper: AnnotationMapper; private readonly _richDescription: boolean; + private readonly _artifactStore: MCPArtifactStore | undefined; private readonly _toolSources = new WeakMap(); private _warnedToolkitMissing = false; @@ -121,6 +125,7 @@ export class MCPServerFactory { this._annotationMapper = new AnnotationMapper(); this._richDescription = options.richDescription ?? false; + this._artifactStore = options.artifactStore; } /** @@ -523,6 +528,12 @@ export class MCPServerFactory { // Handle resources/read requests server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => { const uri = request.params.uri; + if (this._artifactStore && uri.startsWith(ARTIFACT_URI_PREFIX)) { + const artifact = this._artifactStore.read(uri, getCurrentIdentity()); + if (artifact === null) throw new McpError(ErrorCode.InvalidParams, "Artifact not found"); + return { contents: [{ uri, ...artifact }] }; + } + // apcore://system.* management resources — dispatch through the // ExecutionRouter so ACL, approval, audit events, and redaction all @@ -817,9 +828,32 @@ export class MCPServerFactory { }; } - return supportsStructuredOutput(server, extra) - ? addStructuredOutput(result, responseTool) - : result; + if (!supportsStructuredOutput(server, extra)) return result; + const projected = addStructuredOutput(result, responseTool); + this.attachArtifactLinks(projected, responseTool); + return projected; }); } + + private attachArtifactLinks(result: CallToolResult, tool: Tool): void { + const store = this._artifactStore; + const properties = tool.outputSchema?.properties; + if (!store || result.isError || !result.structuredContent || !properties) return; + + const identity = getCurrentIdentity(); + const emitted = new Set(); + for (const [name, schema] of Object.entries(properties)) { + if (typeof schema !== "object" || schema === null) continue; + const definition = schema as Record; + if (definition["x-mcp-artifact"] !== true || definition["x-sensitive"] === true) continue; + const key = result.structuredContent[name]; + if (typeof key !== "string" || key.length !== 32 || emitted.has(key)) continue; + const uri = ARTIFACT_URI_PREFIX + key; + const artifact = store.describe(uri, identity); + if (artifact !== null) { + emitted.add(key); + result.content.push({ type: "resource_link", uri, ...artifact }); + } + } + } } diff --git a/mcp/typescript/src/server/router.ts b/mcp/typescript/src/server/router.ts index 5d43d3d5..48850a37 100644 --- a/mcp/typescript/src/server/router.ts +++ b/mcp/typescript/src/server/router.ts @@ -9,6 +9,7 @@ */ import * as crypto from "node:crypto"; +import { ElicitResultSchema } from "@modelcontextprotocol/sdk/types.js"; import { registerStdioExecution } from "./stdio-output.js"; import { CancelToken, InvalidInputError, isStreamingModule } from "apcore-js"; import { isApprovalResumeToken, supportsScopedCore } from "../adapters/approval.js"; @@ -18,7 +19,7 @@ import { ErrorMapper } from "../adapters/errors.js"; import { ErrorCodes } 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 { MCP_PROGRESS_KEY, MCP_ELICIT_KEY, withCoreInteractions } from "../helpers.js"; import type { ElicitResult } from "../helpers.js"; import { getCurrentIdentity } from "../auth/storage.js"; import type { Identity } from "../auth/types.js"; @@ -567,10 +568,10 @@ export class ExecutionRouter { method: "elicitation/create", params: { message, - ...(requestedSchema ? { requestedSchema } : {}), + requestedSchema: requestedSchema ?? { type: "object", properties: {} }, }, }, - {}, + ElicitResultSchema, ); return (result as ElicitResult) ?? null; }; @@ -591,12 +592,12 @@ export class ExecutionRouter { // is silently broken — the router-level cancel API works but the cancel // signal never reaches the running module. Mirrors Python's first-class // `Context.create(..., cancel_token=...)` (apcore 0.22.0 D-24). - const context = createBridgeContext( + const context = withCoreInteractions(createBridgeContext( contextData, identity, inboundTraceId, cancelToken, - ); + )); // Preserve the pre-fix traceId return contract: return the context's // trace_id only when the call carried "meaningful" trace context diff --git a/mcp/typescript/tests/server/artifact-wire.test.ts b/mcp/typescript/tests/server/artifact-wire.test.ts new file mode 100644 index 00000000..1ba314ed --- /dev/null +++ b/mcp/typescript/tests/server/artifact-wire.test.ts @@ -0,0 +1,79 @@ +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, createIdentity, Executor, Registry } from "apcore-js"; +import { expect, it } from "vitest"; +import { MCPArtifactStore, asyncServe } from "../../src/index.js"; + +it("appends a guarded link and serves its data only to the owning authority", async () => { + const owner = createIdentity("owner", "agent", ["renderer"], {}, { issuer: "fixture" }); + const guest = createIdentity("guest", "agent", ["renderer"], {}, { issuer: "fixture" }); + const store = new MCPArtifactStore({ maxBytes: 100 }); + const key = store.put(Buffer.from("preview"), { name: "preview.png", mimeType: "image/png", owner }); + + const moduleId = "media.preview"; + const registry = new Registry(); + await registry.register(moduleId, { + description: "Return a preview", + inputSchema: { type: "object", properties: {} }, + outputSchema: { + type: "object", + properties: { artifact: { type: "string", "x-mcp-artifact": true } }, + required: ["artifact"], + }, + execute: () => ({ artifact: key }), + }); + const acl = new ACL([{ + callers: ["@external"], targets: [moduleId], effect: "allow", description: "", + conditions: { roles: ["renderer"] }, + }], "deny"); + const app = await asyncServe(new Executor({ registry, acl }) as never, { + async: false, + artifactStore: store, + authenticator: { + async authenticate(headers) { + if (headers.authorization === "Bearer owner") return owner; + if (headers.authorization === "Bearer guest") return guest; + return null; + }, + }, + }); + const server = createServer(app.handler); + const reader = new Client({ name: "artifact-fixture", version: "1" }); + let authorization = "Bearer owner"; + 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 reader.connect(new StreamableHTTPClientTransport(url, { + fetch: (input, init) => { + const headers = new Headers(init?.headers); + headers.set("Authorization", authorization); + return fetch(input, { ...init, headers }); + }, + })); + + const uri = "apcore-artifact://" + key; + const result = await reader.callTool({ name: moduleId, arguments: {} }); + expect(result.isError).not.toBe(true); + expect(result.structuredContent).toEqual({ artifact: key }); + expect(result.content).toEqual([ + { type: "text", text: JSON.stringify({ artifact: key }) }, + { type: "resource_link", uri, name: "preview.png", mimeType: "image/png", size: 7 }, + ]); + expect((await reader.readResource({ uri })).contents).toEqual([ + { uri, blob: Buffer.from("preview").toString("base64"), mimeType: "image/png" }, + ]); + authorization = "Bearer guest"; + expect((await reader.callTool({ name: moduleId, arguments: {} })).content).toEqual([ + { type: "text", text: JSON.stringify({ artifact: key }) }, + ]); + await expect(reader.readResource({ uri })).rejects.toThrow(/artifact not found/i); + } finally { + await reader.close(); + await app.close(); + await new Promise(resolve => server.close(() => resolve())); + } +}); diff --git a/mcp/typescript/tests/server/realtime-interactions.test.ts b/mcp/typescript/tests/server/realtime-interactions.test.ts new file mode 100644 index 00000000..9b9aa24c --- /dev/null +++ b/mcp/typescript/tests/server/realtime-interactions.test.ts @@ -0,0 +1,119 @@ +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { ElicitRequestSchema, ElicitResultSchema, type ElicitRequest } from "@modelcontextprotocol/sdk/types.js"; +import { APCore, Context } from "apcore-js"; +import { describe, expect, it, vi } from "vitest"; +import { MCP_ELICIT_KEY, MCP_PROGRESS_KEY, elicit, reportProgress } from "../../src/helpers.js"; +import { AsyncTaskBridge, type AsyncTaskManagerLike } from "../../src/server/async-task-bridge.js"; +import { ExecutionRouter } from "../../src/server/router.js"; +import { MCPServerFactory } from "../../src/server/factory.js"; +import type { Executor } from "../../src/types.js"; + +type RealtimeContext = Context & { + reportProgress(progress: number, total?: number, message?: string): Promise; + elicit(message: string, schema?: Record): Promise; +}; + +const nativeInteractions = "withProgressReporter" in Context.prototype && "withElicitationHandler" in Context.prototype; + +describe("Core realtime interactions", () => { + it.skipIf(!nativeInteractions)("routes native and legacy module callbacks through the same transport", async () => { + const call = vi.fn(async (_moduleId: string, _args: Record, value: unknown) => { + const context = (value as Context).child("interactions.call") as RealtimeContext; + await context.reportProgress(1, 2, "working"); + await reportProgress(context, 2, 2); + return { reply: await context.elicit("Continue?") }; + }); + const executor = { registry: {}, call } as unknown as Executor; + const sendNotification = vi.fn(async (_notification: Record) => {}); + const sendRequest = vi.fn(async (request: Record, resultSchema: unknown) => { + expect(ElicitRequestSchema.safeParse(request).success).toBe(true); + expect(resultSchema).toBe(ElicitResultSchema); + return { action: "accept", content: { yes: true } }; + }); + + const [content, isError] = await new ExecutionRouter(executor).handleCall("interactions.call", {}, { + _meta: { progressToken: "interaction" }, sendNotification, sendRequest, + }); + + expect(isError).toBe(false); + expect(JSON.parse(content[0].text)).toEqual({ reply: { action: "accept", content: { yes: true } } }); + expect(sendNotification.mock.calls.map(call => call[0])).toEqual([ + { method: "notifications/progress", params: { progressToken: "interaction", progress: 1, total: 2, message: "working" } }, + { method: "notifications/progress", params: { progressToken: "interaction", progress: 2, total: 2 } }, + ]); + expect(sendRequest).toHaveBeenCalledOnce(); + }); + + it.skipIf(!nativeInteractions)("sends progress and asks for a form through a connected MCP client", async () => { + const core = new APCore(); + const name = "interaction.wire"; + await core.register(name, { + description: "Ask a question after reporting progress", + inputSchema: { type: "object" }, + outputSchema: { type: "object" }, + async execute(_inputs: unknown, context: Context) { + const active = context as RealtimeContext; + await active.reportProgress(1, 1, "ready"); + return { response: await active.elicit("Proceed?") }; + }, + }); + const factory = new MCPServerFactory(); + const server = factory.createServer(); + factory.registerHandlers( + server, factory.buildTools(core.registry as never), new ExecutionRouter(core as never), + ); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "realtime-test", version: "1" }, { capabilities: { elicitation: { form: {} } } }); + const ask = vi.fn(async ({ params }: ElicitRequest) => { + expect(params.message).toBe("Proceed?"); + if (params.mode === "url") throw new Error("Expected a form request"); + expect(params.requestedSchema).toEqual({ type: "object", properties: {} }); + return { action: "accept" as const, content: { yes: true } }; + }); + client.setRequestHandler(ElicitRequestSchema, ask); + await server.connect(serverTransport); + await client.connect(clientTransport); + try { + const progress: unknown[] = []; + const result = await client.callTool({ name, arguments: {} }, undefined, { + onprogress: update => { progress.push(update); }, + }); + expect(result.isError).not.toBe(true); + expect(result.structuredContent).toEqual({ response: { action: "accept", content: { yes: true } } }); + expect(progress).toMatchObject([{ progress: 1, total: 1, message: "ready" }]); + expect(ask).toHaveBeenCalledOnce(); + } finally { + await client.close(); + await server.close(); + } + }); + + it.skipIf(!nativeInteractions)("detaches native callbacks from a background session together with legacy callbacks", async () => { + let taskContext: RealtimeContext | undefined; + const manager: AsyncTaskManagerLike = { + async submit(_id, _args, opts) { + taskContext = (opts?.context as Context).child("interactions.background") as RealtimeContext; + return "task"; + }, + getStatus: vi.fn(), getResult: vi.fn(), cancel: vi.fn(), listTasks: vi.fn(), + }; + const bridge = new AsyncTaskBridge(manager); + const progress = vi.fn(async () => {}); + const ask = vi.fn(async () => ({ action: "decline" })); + const root = Context.create(null, null, null, { [MCP_PROGRESS_KEY]: progress, [MCP_ELICIT_KEY]: ask }); + await bridge.submit("interactions.background", {}, root, { callbackSessionKey: "session", progressToken: "t" }); + + await taskContext!.reportProgress(1); + await expect(taskContext!.elicit("Continue?")).resolves.toEqual({ action: "decline" }); + expect(progress).toHaveBeenCalledOnce(); + expect(ask).toHaveBeenCalledOnce(); + + bridge.detachSessionTasks("session"); + await taskContext!.reportProgress(2); + await expect(taskContext!.elicit("Continue?")).resolves.toEqual({ action: "cancel" }); + await expect(elicit(taskContext!, "Continue?")).resolves.toBeNull(); + expect(progress).toHaveBeenCalledOnce(); + expect(ask).toHaveBeenCalledOnce(); + }); +}); diff --git a/toolkit/rust/Cargo.toml b/toolkit/rust/Cargo.toml index 44712969..5070915a 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.5", default-features = false } +apcore = { version = ">=0.33.0, <=1.0.0-beta.1", 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 From 11a1092f173b5490541567cd91c96e95952380bc Mon Sep 17 00:00:00 2001 From: tercel Date: Sun, 29 Nov 2026 08:18:28 +0800 Subject: [PATCH 2/2] fix(surfaces): verify negotiated interactions and final media output Signed-off-by: tercel --- .github/workflows/rust.yml | 4 +- a2a/python/src/apcore_a2a/adapters/parts.py | 2 +- a2a/python/src/apcore_a2a/artifacts.py | 9 ++++ .../tests/server/test_artifact_links.py | 22 +++++--- mcp/docs/features/mcp-server-factory.md | 4 +- mcp/python/src/apcore_mcp/helpers.py | 3 +- mcp/python/src/apcore_mcp/server/router.py | 13 +++-- .../tests/server/test_core_interactions.py | 48 ++++++++++++++---- mcp/rust/Cargo.lock | 2 +- mcp/rust/src/server/router.rs | 4 +- mcp/rust/src/server/session.rs | 11 +++- mcp/rust/src/server/transport.rs | 50 +++++++++++-------- mcp/typescript/src/server/factory.ts | 15 +++--- .../server/realtime-interactions.test.ts | 17 +++++-- 14 files changed, 137 insertions(+), 67 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index f70c4692..cec2a36a 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -26,9 +26,9 @@ env: CORE_CRATE_VERSION: 1.0.0-alpha.5 CORE_CRATE_SHA256: 1d19939071ba2c589815c061dfb1ff827862e5f1f52251e88297d49eec500a90 # MCP uses the native Context interactions from the paired Core candidate. - MCP_CORE_REF: 7573f0de32634e00ba0585d42094613c0add9a76 + MCP_CORE_REF: a3fe0245eecf65bb57c7cca324a7a7b29c6ff553 MCP_CORE_CRATE_VERSION: 1.0.0-beta.1 - MCP_CORE_CRATE_SHA256: 8e7772ee85ac6d1a0538abe1766e6fb192e96a0b657bd05ebf65be60741f47ef + MCP_CORE_CRATE_SHA256: 3b92d75b37a1a8349d47c8aa32b452c67e92171e85391d6c24ce8b3e2bef22d4 jobs: source: diff --git a/a2a/python/src/apcore_a2a/adapters/parts.py b/a2a/python/src/apcore_a2a/adapters/parts.py index 80055a1f..cc59100a 100644 --- a/a2a/python/src/apcore_a2a/adapters/parts.py +++ b/a2a/python/src/apcore_a2a/adapters/parts.py @@ -68,7 +68,7 @@ async def add_artifact_links( policy: ArtifactLinkPolicy, ) -> None: """Add authorized URL parts to an existing finalized data artifact.""" - if isinstance(output, dict) and declaration.is_current(): + if isinstance(output, dict) and declaration.is_current() and declaration.validates_output(output): parts = await policy._resolve_parts(output, declaration.fields, declaration.identity) if declaration.is_current(): artifact.parts.extend(parts) diff --git a/a2a/python/src/apcore_a2a/artifacts.py b/a2a/python/src/apcore_a2a/artifacts.py index 5accd451..84f52554 100644 --- a/a2a/python/src/apcore_a2a/artifacts.py +++ b/a2a/python/src/apcore_a2a/artifacts.py @@ -13,6 +13,7 @@ from a2a.types import Part from apcore import Executor, Identity from apcore.builtin_steps import BuiltinExecute, BuiltinOutputValidation +from apcore.schema.hardening import validate_schema_dict _OPAQUE_ID = re.compile(r"[A-Za-z0-9_-]{1,128}") _HOST = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:[.][a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*") @@ -153,6 +154,14 @@ def is_current(self) -> bool: except Exception: return False + def validates_output(self, output: dict[str, Any]) -> bool: + # Middleware may replace the output after Core's validation step. + try: + return validate_schema_dict(output, self.schema).valid + except Exception: + # Malformed or unresolvable declarations cannot authorize links. + return False + def _artifact_declaration( registry: Any, executor: Any, skill_id: str, identity: Identity diff --git a/a2a/python/tests/server/test_artifact_links.py b/a2a/python/tests/server/test_artifact_links.py index a3872e4a..b27ef1f5 100644 --- a/a2a/python/tests/server/test_artifact_links.py +++ b/a2a/python/tests/server/test_artifact_links.py @@ -18,7 +18,7 @@ class _Result(BaseModel): - artifact: Annotated[str, Field(json_schema_extra={"x-a2a-artifact": True})] + artifact: Annotated[str, Field(min_length=4, json_schema_extra={"x-a2a-artifact": True})] sensitive: Annotated[str, Field(json_schema_extra={"x-a2a-artifact": True, "x-sensitive": True})] @@ -53,8 +53,13 @@ def _call(app: TestClient, principal: str = "alice") -> list[dict]: return response["result"]["task"]["artifacts"][0]["parts"] -@pytest.mark.parametrize("enabled", [False, True]) -def test_link_uses_governed_final_output_and_current_identity(enabled: bool) -> None: +@pytest.mark.parametrize( + ("enabled", "final_artifact", "expect_resolver"), + [(False, "final", False), (True, "final", True), (True, "bad", False)], +) +def test_link_uses_governed_final_output_and_current_identity( + enabled: bool, final_artifact: str, expect_resolver: bool +) -> None: core = APCore() observed: list[tuple[str, str]] = [] @@ -65,7 +70,7 @@ def download() -> _Result: class FinalOutput(Middleware): def after(self, module_id, inputs, output, context): context.identity.attrs["authenticated"] = False - return {**output, "artifact": "final"} + return {**output, "artifact": final_artifact} core.use(FinalOutput()) @@ -89,11 +94,14 @@ async def resolve(artifact_id: str, identity: Identity) -> HostedArtifact | None ) with TestClient(app) as client: - data = {"data": {"artifact": "final", "sensitive": "private"}} - expected = [{"url": _ALLOWED_URL, "filename": "report.txt", "mediaType": "text/plain"}] if enabled else [] + data = {"data": {"artifact": final_artifact, "sensitive": "private"}} + expected = ( + [{"url": _ALLOWED_URL, "filename": "report.txt", "mediaType": "text/plain"}] + if expect_resolver else [] + ) assert _call(client) == [data, *expected] assert _call(client, "bob") == [data] - assert observed == ([("final", "alice"), ("final", "bob")] if enabled else []) + assert observed == ([(final_artifact, "alice"), (final_artifact, "bob")] if expect_resolver else []) @pytest.mark.parametrize( diff --git a/mcp/docs/features/mcp-server-factory.md b/mcp/docs/features/mcp-server-factory.md index 58e55d34..b8cc4fa9 100644 --- a/mcp/docs/features/mcp-server-factory.md +++ b/mcp/docs/features/mcp-server-factory.md @@ -162,7 +162,9 @@ and [HTTP protocol version contract](https://modelcontextprotocol.io/specificati When the Core context exposes interaction callbacks, an executing module can report progress or request an elicitation response using that context. The adapter sends progress when the tool request supplies a progress token, -and attaches elicitation when the client session supports it. Existing MCP +and attaches elicitation when the client session supports form requests. +An empty advertised elicitation capability also enables forms for older +clients. Existing MCP helper functions continue to work. In Rust the native callbacks are available on Stdio and SSE, where the adapter can address a specific client session. diff --git a/mcp/python/src/apcore_mcp/helpers.py b/mcp/python/src/apcore_mcp/helpers.py index 79c713bf..72a6e8d6 100644 --- a/mcp/python/src/apcore_mcp/helpers.py +++ b/mcp/python/src/apcore_mcp/helpers.py @@ -36,7 +36,8 @@ def _bind_core_elicitation(context: _Context) -> _Context: return context async def handle(message: str, requested_schema: dict[str, Any] | None) -> Any: - result = await callback(message, requested_schema) + schema = requested_schema if requested_schema is not None else {"type": "object", "properties": {}} + result = await callback(message, schema) if result is not None: action, content = result["action"], result.get("content") if action == "accept" and isinstance(content, dict): diff --git a/mcp/python/src/apcore_mcp/server/router.py b/mcp/python/src/apcore_mcp/server/router.py index c6e4dcd3..d46ce9c1 100644 --- a/mcp/python/src/apcore_mcp/server/router.py +++ b/mcp/python/src/apcore_mcp/server/router.py @@ -18,7 +18,6 @@ from apcore.registry.types import ModuleDescriptor from apcore.registry.version import matches_version_hint from apcore.trace_context import TraceContext, TraceParent -from mcp import types as mcp_types from mcp.server.lowlevel.server import request_ctx from mcp.server.session import ServerSession @@ -620,12 +619,12 @@ async def _elicit_callback( ) context = _bind_core_progress(context) - if session is not None and ( - not isinstance(session, ServerSession) - or session.check_client_capability( - mcp_types.ClientCapabilities(elicitation=mcp_types.ElicitationCapability()) - ) - ): + supports_form = session is not None + if isinstance(session, ServerSession): + params = session.client_params + elicitation = params.capabilities.elicitation if params is not None else None + supports_form = elicitation is not None and (elicitation.form is not None or elicitation.url is None) + if supports_form: context = _bind_core_elicitation(context) # Explicit SDK hint, then MCP metadata, then descriptor default. diff --git a/mcp/python/tests/server/test_core_interactions.py b/mcp/python/tests/server/test_core_interactions.py index f649705b..86b30904 100644 --- a/mcp/python/tests/server/test_core_interactions.py +++ b/mcp/python/tests/server/test_core_interactions.py @@ -24,10 +24,24 @@ class _Inputs(BaseModel): @pytest.mark.asyncio -@pytest.mark.parametrize("supports_elicitation", [True, False]) -async def test_core_progress_and_elicitation_on_mcp_wire(supports_elicitation: bool) -> None: +@pytest.mark.parametrize( + ("capability", "supports_elicitation"), + [ + (types.ElicitationCapability(form=types.FormElicitationCapability()), True), + (types.ElicitationCapability(), True), + (types.ElicitationCapability(url=types.UrlElicitationCapability()), False), + (None, False), + ], +) +@pytest.mark.parametrize("explicit_schema", [True, False]) +async def test_core_progress_and_elicitation_on_mcp_wire( + capability: types.ElicitationCapability | None, supports_elicitation: bool, explicit_schema: bool +) -> None: schema = {"type": "object", "properties": {"confirmed": {"type": "boolean"}}} + expected_schema = schema if explicit_schema else {"type": "object", "properties": {}} + accepted_content = {"confirmed": True} if explicit_schema else {} observed: list[tuple[float, float | None, str | None]] = [] + prompts: list[str] = [] class Tool: description = "Report progress and request optional confirmation" @@ -36,15 +50,19 @@ class Tool: async def execute(self, inputs: dict[str, Any], context: Context) -> dict[str, Any]: await context.report_progress(1, 2, "Preparing") - answer = await context.elicit("Confirm?", schema) - confirmed = answer is not None and answer.action == "accept" and answer.content == {"confirmed": True} + if explicit_schema: + answer = await context.elicit("Confirm?", schema) + else: + answer = await context.elicit("Confirm?") + confirmed = answer is not None and answer.action == "accept" and answer.content == accepted_content return {"confirmed": confirmed} async def elicit(context: Any, request: types.ElicitRequestParams) -> types.ElicitResult: assert isinstance(request, types.ElicitRequestFormParams) + prompts.append(request.message) assert request.message == "Confirm?" - assert request.requestedSchema == schema - return types.ElicitResult(action="accept", content={"confirmed": True}) + assert request.requestedSchema == expected_schema + return types.ElicitResult(action="accept", content=accepted_content) async def progress(count: float, total: float | None, message: str | None) -> None: observed.append((count, total, message)) @@ -62,15 +80,27 @@ async def progress(count: float, total: float | None, message: str | None) -> No with anyio.fail_after(5): async with anyio.create_task_group() as group: group.start_soon(TransportManager()._run_scoped, server, read_server, send_server, init, "test") - callback = elicit if supports_elicitation else None - async with ClientSession(read_client, send_client, elicitation_callback=callback) as session: - await session.initialize() + async with ClientSession(read_client, send_client, elicitation_callback=elicit) as session: + await session.send_request( + types.ClientRequest( + types.InitializeRequest( + params=types.InitializeRequestParams( + protocolVersion=types.LATEST_PROTOCOL_VERSION, + capabilities=types.ClientCapabilities(elicitation=capability), + clientInfo=types.Implementation(name="core-interaction-test", version="1"), + ) + ) + ), + types.InitializeResult, + ) + await session.send_notification(types.ClientNotification(types.InitializedNotification())) result = await session.call_tool("test.interaction", {}, progress_callback=progress) group.cancel_scope.cancel() assert result.isError is False assert result.structuredContent == {"confirmed": supports_elicitation} assert observed == [(1, 2, "Preparing")] + assert prompts == (["Confirm?"] if supports_elicitation else []) @pytest.mark.asyncio diff --git a/mcp/rust/Cargo.lock b/mcp/rust/Cargo.lock index 4b63a46f..5a247136 100644 --- a/mcp/rust/Cargo.lock +++ b/mcp/rust/Cargo.lock @@ -100,7 +100,7 @@ dependencies = [ name = "apcore" version = "1.0.0-beta.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e7772ee85ac6d1a0538abe1766e6fb192e96a0b657bd05ebf65be60741f47ef" +checksum = "3b92d75b37a1a8349d47c8aa32b452c67e92171e85391d6c24ce8b3e2bef22d4" dependencies = [ "async-stream", "async-trait", diff --git a/mcp/rust/src/server/router.rs b/mcp/rust/src/server/router.rs index bb55eafc..bfd5c5d9 100644 --- a/mcp/rust/src/server/router.rs +++ b/mcp/rust/src/server/router.rs @@ -301,7 +301,9 @@ fn native_elicitation_handler( let session = Arc::clone(&session); let lifetime = lifetime.clone(); Box::pin(async move { - let schema = request.requested_schema.unwrap_or_else(|| json!({})); + let schema = request + .requested_schema + .unwrap_or_else(|| json!({"type": "object", "properties": {}})); let reply = during_interaction(&lifetime, async { session .elicit_form(&request.message, &schema) diff --git a/mcp/rust/src/server/session.rs b/mcp/rust/src/server/session.rs index 6c5e9dc2..0f9d1d0e 100644 --- a/mcp/rust/src/server/session.rs +++ b/mcp/rust/src/server/session.rs @@ -250,7 +250,14 @@ impl McpSession { #[async_trait] impl SessionHandle for McpSession { fn supports_elicitation(&self) -> bool { - McpSession::supports_elicitation(self) + lock(&self.client_capabilities) + .as_ref() + .and_then(|caps| caps.get("elicitation")) + .and_then(Value::as_object) + .is_some_and(|elicitation| { + elicitation.get("form").is_some_and(Value::is_object) + || elicitation.get("url").is_none_or(Value::is_null) + }) } async fn elicit_form( @@ -258,7 +265,7 @@ impl SessionHandle for McpSession { message: &str, requested_schema: &Value, ) -> Result> { - if !self.supports_elicitation() { + if !McpSession::supports_elicitation(self) { return Err(SessionError::ElicitationUnsupported.into()); } diff --git a/mcp/rust/src/server/transport.rs b/mcp/rust/src/server/transport.rs index bd0a9256..965e2943 100644 --- a/mcp/rust/src/server/transport.rs +++ b/mcp/rust/src/server/transport.rs @@ -4371,7 +4371,7 @@ mod tests { type RetainedContext = Arc>>>; - struct NativeInteraction(RetainedContext); + struct NativeInteraction(RetainedContext, Option); #[async_trait::async_trait] impl apcore::Module for NativeInteraction { @@ -4395,15 +4395,15 @@ mod tests { context .report_progress(2.0, Some(3.0), Some("native progress")) .await?; - let reply = context - .elicit("Native prompt?", serde_json::json!({"type":"object"})) - .await?; + let reply = context.elicit("Native prompt?", self.1.clone()).await?; *self.0.lock().unwrap() = Some(context.clone()); Ok(serde_json::json!({"reply":reply})) } } - fn native_interaction_handler() -> ( + fn native_interaction_handler( + requested_schema: Option, + ) -> ( Arc, String, RetainedContext, @@ -4413,7 +4413,7 @@ mod tests { registry .register_module( "demo.native", - Box::new(NativeInteraction(Arc::clone(&retained))), + Box::new(NativeInteraction(Arc::clone(&retained), requested_schema)), ) .unwrap(); let bridge = crate::APCoreMCP::builder() @@ -4439,17 +4439,14 @@ mod tests { }) } - fn native_prompt(progress: &Value, prompt: &Value) { + fn native_prompt(progress: &Value, prompt: &Value, expected_schema: &Value) { assert_eq!(progress["method"], "notifications/progress"); assert_eq!(progress["params"]["progressToken"], "native"); assert_eq!(progress["params"]["progress"], 2.0); assert_eq!(progress["params"]["message"], "native progress"); assert_eq!(prompt["method"], "elicitation/create"); assert_eq!(prompt["params"]["message"], "Native prompt?"); - assert_eq!( - prompt["params"]["requestedSchema"], - serde_json::json!({"type":"object"}) - ); + assert_eq!(&prompt["params"]["requestedSchema"], expected_schema); } fn native_result(response: &Value) -> Value { @@ -4460,7 +4457,9 @@ mod tests { #[tokio::test] async fn stdio_delivers_native_context_progress_and_elicitation() { - let (handler, name, retained) = native_interaction_handler(); + let schema = + serde_json::json!({"type":"object","properties":{"confirmed":{"type":"boolean"}}}); + let (handler, name, retained) = native_interaction_handler(Some(schema.clone())); let tm = TransportManager::new(None); let (client, server) = tokio::io::duplex(64 * 1024); let (client_read, mut client_write) = tokio::io::split(client); @@ -4480,7 +4479,7 @@ mod tests { let progress = recv(&mut client_lines).await; assert_eq!(progress["method"], "notifications/progress"); let prompt = recv(&mut client_lines).await; - native_prompt(&progress, &prompt); + native_prompt(&progress, &prompt, &schema); send( &mut client_write, serde_json::json!({ @@ -4511,7 +4510,7 @@ mod tests { send(&mut client_write, native_call(&name, 3)).await; let progress = recv(&mut client_lines).await; let prompt = recv(&mut client_lines).await; - native_prompt(&progress, &prompt); + native_prompt(&progress, &prompt, &schema); send(&mut client_write, cancel_request(3.into())).await; send( &mut client_write, @@ -4532,14 +4531,14 @@ mod tests { #[tokio::test] async fn sse_delivers_native_context_interactions_on_the_calling_session() { - let (handler, name, _) = native_interaction_handler(); + let (handler, name, _) = native_interaction_handler(None); let (app, _) = sse_test_app_parts_with(Arc::new(TransportManager::new(None)), handler); let (mut body, id) = open_sse_session(&app).await; assert_eq!( post_sse_raw( &app, &id, - native_init(serde_json::json!({"elicitation":{}})) + native_init(serde_json::json!({"elicitation":{"form":{}}})) ) .await, StatusCode::ACCEPTED @@ -4550,7 +4549,11 @@ mod tests { StatusCode::ACCEPTED ); let messages = collect_sse_messages(&mut body, 2, |_| true).await; - native_prompt(&messages[0], &messages[1]); + native_prompt( + &messages[0], + &messages[1], + &serde_json::json!({"type":"object","properties":{}}), + ); assert_eq!( post_sse_raw( &app, @@ -4570,8 +4573,13 @@ mod tests { } #[tokio::test] - async fn stdio_without_elicitation_capability_gets_no_native_prompt() { - let (handler, name, _) = native_interaction_handler(); + async fn stdio_without_form_elicitation_gets_no_native_prompt() { + assert_no_native_form_prompt(serde_json::json!({})).await; + assert_no_native_form_prompt(serde_json::json!({"elicitation":{"url":{}}})).await; + } + + async fn assert_no_native_form_prompt(capabilities: Value) { + let (handler, name, _) = native_interaction_handler(None); let tm = TransportManager::new(None); let (client, server) = tokio::io::duplex(64 * 1024); let (client_read, mut client_write) = tokio::io::split(client); @@ -4581,7 +4589,7 @@ mod tests { tm.run_stdio_with_io(server_read, server_write, handler.as_ref()) .await }); - send(&mut client_write, native_init(serde_json::json!({}))).await; + send(&mut client_write, native_init(capabilities)).await; assert_eq!(recv(&mut client_lines).await["id"], 1); send(&mut client_write, native_call(&name, 2)).await; assert_eq!( @@ -4600,7 +4608,7 @@ mod tests { use http_body_util::BodyExt; use tower::ServiceExt; - let (handler, name, _) = native_interaction_handler(); + let (handler, name, _) = native_interaction_handler(None); let sessions = handler.session_registry().unwrap(); let tm = Arc::new(TransportManager::new(None)); let app = tm.build_streamable_http_app(handler, None); diff --git a/mcp/typescript/src/server/factory.ts b/mcp/typescript/src/server/factory.ts index 25432c32..5e7ee080 100644 --- a/mcp/typescript/src/server/factory.ts +++ b/mcp/typescript/src/server/factory.ts @@ -711,6 +711,8 @@ export class MCPServerFactory { const toolArgs = (args ?? {}) as Record; let responseTool = tool; + const elicitation = server.getClientCapabilities?.()?.elicitation; + const canElicit = elicitation !== undefined && (elicitation.form !== undefined || elicitation.url === undefined); // Build HandleCallExtra from MCP SDK extra const handleCallExtra: HandleCallExtra = { onOutputDescriptor(descriptor) { @@ -721,7 +723,7 @@ export class MCPServerFactory { ? (notification: Record) => extra.sendNotification(notification as any) : undefined, - sendRequest: extra?.sendRequest + sendRequest: canElicit && extra?.sendRequest ? (request: Record, resultSchema: unknown) => (extra.sendRequest as Function)(request, resultSchema) : undefined, @@ -769,14 +771,9 @@ export class MCPServerFactory { // the call extra so the router can attach it to the apcore Context. // Mirrors Python's factory pattern (factory.py:232-234) which reads // auth_identity_var.get() and forwards into extra["identity"]. - try { - const { getCurrentIdentity } = await import("../auth/storage.js"); - const identity = getCurrentIdentity(); - if (identity !== null) { - (handleCallExtra as HandleCallExtra & { identity?: unknown }).identity = identity; - } - } catch { - // auth module not available — skip silently (auth is optional). + const identity = getCurrentIdentity(); + if (identity !== null) { + handleCallExtra.identity = identity; } // Dispatch to approval bridge meta-tool if applicable (AFTER async bridge, diff --git a/mcp/typescript/tests/server/realtime-interactions.test.ts b/mcp/typescript/tests/server/realtime-interactions.test.ts index 9b9aa24c..25ae700a 100644 --- a/mcp/typescript/tests/server/realtime-interactions.test.ts +++ b/mcp/typescript/tests/server/realtime-interactions.test.ts @@ -45,7 +45,12 @@ describe("Core realtime interactions", () => { expect(sendRequest).toHaveBeenCalledOnce(); }); - it.skipIf(!nativeInteractions)("sends progress and asks for a form through a connected MCP client", async () => { + it.skipIf(!nativeInteractions).each([ + { description: "form capability", capabilities: { elicitation: { form: {} } }, expectsPrompt: true }, + { description: "legacy capability", capabilities: { elicitation: {} }, expectsPrompt: true }, + { description: "URL-only capability", capabilities: { elicitation: { url: {} } }, expectsPrompt: false }, + { description: "no capability", capabilities: {}, expectsPrompt: false }, + ])("sends progress and respects $description on a connected MCP client", async ({ capabilities, expectsPrompt }) => { const core = new APCore(); const name = "interaction.wire"; await core.register(name, { @@ -64,14 +69,14 @@ describe("Core realtime interactions", () => { server, factory.buildTools(core.registry as never), new ExecutionRouter(core as never), ); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - const client = new Client({ name: "realtime-test", version: "1" }, { capabilities: { elicitation: { form: {} } } }); + const client = new Client({ name: "realtime-test", version: "1" }, { capabilities }); const ask = vi.fn(async ({ params }: ElicitRequest) => { expect(params.message).toBe("Proceed?"); if (params.mode === "url") throw new Error("Expected a form request"); expect(params.requestedSchema).toEqual({ type: "object", properties: {} }); return { action: "accept" as const, content: { yes: true } }; }); - client.setRequestHandler(ElicitRequestSchema, ask); + if (expectsPrompt) client.setRequestHandler(ElicitRequestSchema, ask); await server.connect(serverTransport); await client.connect(clientTransport); try { @@ -80,9 +85,11 @@ describe("Core realtime interactions", () => { onprogress: update => { progress.push(update); }, }); expect(result.isError).not.toBe(true); - expect(result.structuredContent).toEqual({ response: { action: "accept", content: { yes: true } } }); + expect(result.structuredContent).toEqual({ + response: expectsPrompt ? { action: "accept", content: { yes: true } } : null, + }); expect(progress).toMatchObject([{ progress: 1, total: 1, message: "ready" }]); - expect(ask).toHaveBeenCalledOnce(); + expect(ask).toHaveBeenCalledTimes(expectsPrompt ? 1 : 0); } finally { await client.close(); await server.close();