diff --git a/a2a/conformance/fixtures/error_mapping.json b/a2a/conformance/fixtures/error_mapping.json index 6f833457..3619d6a3 100644 --- a/a2a/conformance/fixtures/error_mapping.json +++ b/a2a/conformance/fixtures/error_mapping.json @@ -42,6 +42,36 @@ "Access denied" ] }, + { + "id": "policy_denied_is_a_masked_access_decision", + "input": { + "exception": "PolicyDeniedError", + "message": "Denied by private-policy-rule" + }, + "disclose_refusal_reason": true, + "expected_error_code": -32040, + "expected_error_message": [ + "Access denied" + ], + "expected_message_excludes": [ + "private-policy-rule" + ] + }, + { + "id": "policy_evaluation_error_stays_a_masked_server_failure", + "input": { + "exception": "PolicyEvaluationError", + "message": "Unexpected private-policy-rule exception" + }, + "disclose_refusal_reason": true, + "expected_error_code": -32603, + "expected_error_message": [ + "Policy evaluation failed" + ], + "expected_message_excludes": [ + "private-policy-rule" + ] + }, { "id": "approval_denied_sanitized", "description": "ApprovalDeniedError -> -32041 with the fixed message \"Approval denied\". Must NOT fall into the -32603 catch-all: \"Internal server error\" is the canonical retryable failure, and a human explicitly refused this call.", diff --git a/a2a/docs/features/adapters.md b/a2a/docs/features/adapters.md index 425b9954..f54b4d58 100644 --- a/a2a/docs/features/adapters.md +++ b/a2a/docs/features/adapters.md @@ -542,8 +542,8 @@ ID. The trusted asynchronous resolver receives that ID and the authenticated `Identity`. It returns `HostedArtifact` metadata for an authorized download or reports that no link is available. -The Python adapter also projects a direct `ArtifactRef` field declared with the -Core artifact assertions and `x-a2a-artifact: true`. It checks that the host's +All three adapters also project a direct `ArtifactRef` field declared with the +Core artifact assertions and `x-a2a-artifact: true`. Each checks that the host's issued media type and byte count match the final structured result before adding the link. The existing opaque-ID fields are still supported. diff --git a/a2a/docs/features/server-core.md b/a2a/docs/features/server-core.md index d95a0e08..f371f4e2 100644 --- a/a2a/docs/features/server-core.md +++ b/a2a/docs/features/server-core.md @@ -439,9 +439,11 @@ Auth exempt paths include `{"/.well-known/agent.json", "/.well-known/agent-card. - `ApCoreAgentExecutor` uses duck-typing for both Registry and Executor - Task lifecycle and state machine are managed by a2a-sdk's `DefaultRequestHandler` - JSON-RPC dispatch and transport are handled by a2a-sdk's `A2AStarletteApplication` -- Governance refusals carry their own codes — `-32040` ACL, `-32041` approval denied, - `-32042` approval timed out — each with a fixed message and a `rejected` task state. - `-32001` means only "unknown or non-owned task id" (srs FR-ERR-003/009/010/012) +- Governance refusals have fixed messages and a `rejected` task state. `-32040` + covers ACL and policy denial. `-32041` covers approval denial and `-32042` + covers approval timeout. Policy evaluation failure uses `-32603` and a + `failed` task state. `-32001` means an unknown or non-owned task ID + (SRS FR-ERR-003/009/010/012/013). - `A2AServerFactory.create()` returns `tuple[Starlette, AgentCard]` (Pydantic model) ## Test Modules diff --git a/a2a/docs/spec/srs.md b/a2a/docs/spec/srs.md index e9ac75f0..dc74374f 100644 --- a/a2a/docs/spec/srs.md +++ b/a2a/docs/spec/srs.md @@ -1095,7 +1095,7 @@ Code -32040 is a JSON-RPC implementation-defined server error (the §13.2 "JSON- **Rationale:** Unknown exceptions must never leak internal details. A generic error message ensures security while still indicating a server-side failure. **Acceptance Criteria:** -1. Any exception not matched by FR-ERR-001 through FR-ERR-007 or FR-ERR-009 through FR-ERR-010 SHALL produce JSON-RPC error -32603. +1. Any exception without an explicit mapping SHALL produce JSON-RPC error -32603. 2. The error message SHALL be "Internal server error" (the same fixed generic message used for `ModuleExecuteError` per FR-ERR-004, so unrecognized and execution errors are indistinguishable to the caller). 3. The error SHALL NOT include stack traces, file paths, or internal variable values. 4. The JSON-RPC error object is `{code, message}` only; no `data` field is emitted in v0.4. @@ -1154,7 +1154,7 @@ Code -32040 is a JSON-RPC implementation-defined server error (the §13.2 "JSON- | **Priority** | P1 | | **PRD Trace** | FR-007 | -**Description:** The system SHALL provide a configuration flag `disclose_refusal_reason` (default `false`) that, when enabled, forwards apcore's own sanitized message for the three governance refusal codes (`ACL_DENIED`, `APPROVAL_DENIED`, `APPROVAL_TIMEOUT`) in place of the fixed per-class string. +**Description:** The system SHALL provide a configuration flag `disclose_refusal_reason` (default `false`) that, when enabled, forwards apcore's own sanitized message for `ACL_DENIED`, `APPROVAL_DENIED`, and `APPROVAL_TIMEOUT` in place of the fixed per-class string. **Rationale:** The *class* of a refusal is always conveyed (FR-ERR-003, FR-ERR-009, FR-ERR-010); the *detail* is a deployment choice. A server whose callers are its own agents wants apcore's reason — `Access denied: caller '…' cannot access module '…'` — which is what the apcore MCP binding reports today, so an operator comparing the two transports otherwise sees the reason on one and a fixed string on the other. A server facing untrusted callers keeps the default and discloses nothing. @@ -1175,18 +1175,36 @@ Code -32040 is a JSON-RPC implementation-defined server error (the §13.2 "JSON- | **Priority** | P0 | | **PRD Trace** | FR-007 | -**Description:** On the task-status surface, the system SHALL place a task refused by governance (`ACL_DENIED`, `APPROVAL_DENIED`, `APPROVAL_TIMEOUT`) into `TASK_STATE_REJECTED` rather than `TASK_STATE_FAILED`. +**Description:** On the task-status surface, the system SHALL place a task refused by governance (`ACL_DENIED`, `APPROVAL_DENIED`, `APPROVAL_TIMEOUT`, `POLICY_DENIED`) into `TASK_STATE_REJECTED` rather than `TASK_STATE_FAILED`. **Rationale:** A2A 1.0 defines `TASK_STATE_REJECTED` as a terminal state, and a policy refusal is exactly what it describes. This matters more than the JSON-RPC code on the `message/send` path, where the response is a JSON-RPC `result` and the error code never reaches the caller at all — the status state and its message are the entire payload the caller receives. **Acceptance Criteria:** -1. A task refused by `ACL_DENIED`, `APPROVAL_DENIED` or `APPROVAL_TIMEOUT` SHALL reach `TASK_STATE_REJECTED`. +1. A task refused by `ACL_DENIED`, `APPROVAL_DENIED`, `APPROVAL_TIMEOUT`, or `POLICY_DENIED` SHALL reach `TASK_STATE_REJECTED`. 2. The status message SHALL be the same text the `ErrorMapper` produces for that code, so the two surfaces cannot diverge. 3. Every other failure SHALL continue to reach `TASK_STATE_FAILED`; `EXECUTION_CANCELLED` SHALL continue to reach `TASK_STATE_CANCELED` and `APPROVAL_PENDING` `TASK_STATE_INPUT_REQUIRED`. 4. `TASK_STATE_REJECTED` is terminal: a rejected task SHALL NOT be resumable, and `tasks/cancel` on it SHALL return -32002 like any other terminal state. --- +#### FR-ERR-013: Distinguish policy refusal from policy evaluation failure + +| Field | Value | +|-------|-------| +| **ID** | FR-ERR-013 | +| **Priority** | P0 | +| **PRD Trace** | FR-007 | + +1. `POLICY_DENIED` SHALL produce JSON-RPC code -32040 with the fixed message + `"Access denied"` and task state `TASK_STATE_REJECTED`. +2. `POLICY_EVALUATION_ERROR` SHALL produce JSON-RPC code -32603 with the fixed + message `"Policy evaluation failed"` and task state `TASK_STATE_FAILED`. +3. Both outcomes SHALL omit `data` and policy details, including when + `disclose_refusal_reason` is enabled. The adapter SHALL suppress the + original policy message, exception, and guidance in its diagnostics. + +--- + ### 3.8 FR-CLI: Client Module Requirements --- @@ -3163,7 +3181,7 @@ The system consumes A2A types, JSON-RPC handling, and SSE utilities from the `a2 | FR-004 | message/send | P0 | FR-MSG-001, FR-MSG-003, FR-MSG-004 | | FR-005 | Task Lifecycle (State Machine) | P0 | FR-TSK-001, FR-TSK-002, FR-TSK-003 | | FR-006 | Execution Routing | P0 | FR-EXE-001, FR-EXE-002, FR-EXE-003 | -| FR-007 | Error Mapping | P0 | FR-ERR-001, FR-ERR-002, FR-ERR-003, FR-ERR-004, FR-ERR-005, FR-ERR-006, FR-ERR-007, FR-ERR-008, FR-ERR-009, FR-ERR-010, FR-ERR-011, FR-ERR-012 | +| FR-007 | Error Mapping | P0 | FR-ERR-001, FR-ERR-002, FR-ERR-003, FR-ERR-004, FR-ERR-005, FR-ERR-006, FR-ERR-007, FR-ERR-008, FR-ERR-009, FR-ERR-010, FR-ERR-011, FR-ERR-012, FR-ERR-013 | | FR-008 | tasks/get, ListTasks, tasks/cancel | P0 | FR-TSK-004, FR-TSK-005, FR-TSK-006 | | FR-009 | SSE Streaming (message/stream) | P0 | FR-MSG-002, FR-MSG-005, FR-MSG-006 | | FR-010 | A2A Client | P0 | FR-CLI-001, FR-CLI-002, FR-CLI-003, FR-CLI-004, FR-CLI-005 | @@ -3225,6 +3243,7 @@ The system consumes A2A types, JSON-RPC handling, and SSE utilities from the `a2 | FR-ERR-010 | FR-007 | P0 | | FR-ERR-011 | FR-007 | P1 | | FR-ERR-012 | FR-007 | P0 | +| FR-ERR-013 | FR-007 | P0 | | FR-CLI-001 | FR-010 | P0 | | FR-CLI-002 | FR-010 | P0 | | FR-CLI-003 | FR-010 | P0 | diff --git a/a2a/docs/spec/tech-design.md b/a2a/docs/spec/tech-design.md index 14e47805..23450e2e 100644 --- a/a2a/docs/spec/tech-design.md +++ b/a2a/docs/spec/tech-design.md @@ -631,7 +631,7 @@ Reuses the same approach as apcore-mcp's `SchemaConverter`: deep-copy schemas, i #### 4.3.4 `ErrorMapper` -**Implements**: FR-ERR-001 through FR-ERR-008 +**Implements**: FR-ERR-001 through FR-ERR-013 **File**: `adapters/errors.py` @@ -647,6 +647,8 @@ Reuses the same approach as apcore-mcp's `SchemaConverter`: deep-copy schemas, i "ACL_DENIED": (-32040, "Access denied", True), "APPROVAL_DENIED": (-32041, "Approval denied", True), "APPROVAL_TIMEOUT": (-32042, "Approval timed out", True), + "POLICY_DENIED": (-32040, "Access denied", False), + "POLICY_EVALUATION_ERROR": (-32603, "Policy evaluation failed", False), "MODULE_TIMEOUT": (-32603, "Execution timeout", False), "EXECUTION_CANCELLED": (-32603, "Execution cancelled", False), "CALL_DEPTH_EXCEEDED": (-32603, "Safety limit exceeded", True), @@ -679,7 +681,8 @@ Reuses the same approach as apcore-mcp's `SchemaConverter`: deep-copy schemas, i // Same error-code mapping; messages are sanitized (strips paths/tracebacks, caps 500 chars). // MODULE_NOT_FOUND->-32601; SCHEMA_VALIDATION_ERROR->-32602; MODULE_TIMEOUT->-32603 // ("Execution timeout"); EXECUTION_CANCELLED->-32603; ACL_DENIED->-32040; - // APPROVAL_DENIED->-32041; APPROVAL_TIMEOUT->-32042; others->-32603. + // APPROVAL_DENIED->-32041; APPROVAL_TIMEOUT->-32042; + // POLICY_DENIED->-32040; POLICY_EVALUATION_ERROR->-32603. class ErrorMapper { format(error, context?): Record toJsonRpcError(error): { code: number; message: string } @@ -2869,6 +2872,12 @@ mapping behavior. See Section 4.3.4 for the complete error mapping from apcore exceptions to JSON-RPC error codes. +`POLICY_DENIED` maps to `-32040` with `"Access denied"` and terminal task state +`rejected`. `POLICY_EVALUATION_ERROR` maps to `-32603` with `"Policy evaluation +failed"` and terminal task state `failed`. These outcomes carry fixed messages +and suppress error details in responses and adapter logs regardless of +`disclose_refusal_reason` (FR-ERR-013). + ### 9.2 JSON-RPC Protocol Errors | Condition | Code | Message | @@ -3747,7 +3756,7 @@ All client-provided strings in log messages are truncated to 1,000 characters an | `adapters/agent_card.py` (AgentCardBuilder) | FR-AGC-001, FR-AGC-002, FR-AGC-003, FR-AGC-004, FR-AGC-005 | | `adapters/skill_mapper.py` (SkillMapper) | FR-SKL-001, FR-SKL-002, FR-SKL-003, FR-SKL-004 | | `adapters/schema.py` (SchemaConverter) | FR-MSG-003, FR-MSG-004 | -| `adapters/errors.py` (ErrorMapper) | FR-ERR-001, FR-ERR-002, FR-ERR-003, FR-ERR-004, FR-ERR-005, FR-ERR-006, FR-ERR-007, FR-ERR-008 | +| `adapters/errors.py` (ErrorMapper) | FR-ERR-001 through FR-ERR-013 | | `adapters/parts.py` (PartConverter) | FR-MSG-003, FR-MSG-004 | | `server/factory.py` (A2AServerFactory) | FR-SRV-001, FR-SRV-002, FR-AGC-001 | | `server/router.py` (ExecutionRouter) | FR-EXE-001, FR-EXE-002, FR-EXE-003, FR-MSG-001, FR-MSG-002 | diff --git a/a2a/python/pyproject.toml b/a2a/python/pyproject.toml index ce8693ff..83a6aef9 100644 --- a/a2a/python/pyproject.toml +++ b/a2a/python/pyproject.toml @@ -56,7 +56,7 @@ apcore-a2a = "apcore_a2a.__main__:main" [project.urls] Homepage = "https://aiperceivable.com" Repository = "https://github.com/aiperceivable/apcore-surfaces/tree/main/a2a/python" -Documentation = "https://github.com/aiperceivable/apcore-a2a-python#readme" +Documentation = "https://aiperceivable.github.io/apcore-surfaces/a2a/" Issues = "https://github.com/aiperceivable/apcore-surfaces/issues" [tool.hatch.build.targets.wheel] diff --git a/a2a/python/src/apcore_a2a/adapters/errors.py b/a2a/python/src/apcore_a2a/adapters/errors.py index ac9771a7..53e22119 100644 --- a/a2a/python/src/apcore_a2a/adapters/errors.py +++ b/a2a/python/src/apcore_a2a/adapters/errors.py @@ -43,7 +43,7 @@ # Public alias for the server layer, which needs the same partition to decide # TASK_STATE_REJECTED (srs FR-ERR-012) without re-deriving it. -GOVERNANCE_REFUSAL_CODES: frozenset[str] = frozenset(_GOVERNANCE_REFUSALS) +GOVERNANCE_REFUSAL_CODES: frozenset[str] = frozenset(_GOVERNANCE_REFUSALS) | {ErrorCodes.POLICY_DENIED} _GOVERNANCE_CODES: dict[str, int] = { ErrorCodes.ACL_DENIED: _CODE_ACCESS_DENIED, @@ -96,12 +96,16 @@ def to_jsonrpc_error(self, error: Exception) -> dict[str, Any]: Returns: Dict with "code" (int) and "message" (str) keys. """ - # Log full detail for server-side diagnosis - logger.error("A2A error: %s", error, exc_info=True) - - # Check for apcore-style errors with a .code attribute error_code = getattr(error, "code", None) - + # Policy errors always use fixed messages, including when disclosure + # is enabled for ACL and approval refusals. + if error_code == ErrorCodes.POLICY_DENIED: + return {"code": _CODE_ACCESS_DENIED, "message": "Access denied"} + if error_code == ErrorCodes.POLICY_EVALUATION_ERROR: + return {"code": _CODE_INTERNAL_ERROR, "message": "Policy evaluation failed"} + + # Log full detail for server-side diagnosis for other error classes. + logger.error("A2A error: %s", error, exc_info=True) if error_code is not None: return self._handle_apcore_error(error, error_code) diff --git a/a2a/python/src/apcore_a2a/artifacts.py b/a2a/python/src/apcore_a2a/artifacts.py index ca8d41a5..837230d0 100644 --- a/a2a/python/src/apcore_a2a/artifacts.py +++ b/a2a/python/src/apcore_a2a/artifacts.py @@ -11,7 +11,7 @@ from urllib.parse import urlsplit from a2a.types import Part -from apcore import Executor, Identity +from apcore import Executor, Identity, SchemaParseError from apcore.builtin_steps import ( BuiltinACLCheck, BuiltinApprovalGate, @@ -27,12 +27,12 @@ _BuiltinPostValidationPolicy, ) from apcore.schema.hardening import validate_schema_dict +from pydantic import ValidationError try: - from apcore._artifact_projection import is_direct_artifact_reference, parse_artifact_reference + from apcore.artifacts import ArtifactRef except ImportError: - is_direct_artifact_reference = None # type: ignore[assignment] - parse_artifact_reference = None # type: ignore[assignment] + ArtifactRef = None # type: ignore[assignment] _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])?)*") @@ -42,6 +42,8 @@ _SCHEMA_APPLICATORS = frozenset( {"$ref", "$dynamicRef", "allOf", "anyOf", "oneOf", "if", "then", "else", "dependentSchemas", "patternProperties"} ) +_REFERENCE_ASSERTIONS = frozenset({"x-artifact-ref", "x-media-types", "x-max-bytes"}) +_REFERENCE_FIELDS = frozenset({"type", "title", "description"}) _GOVERNED_OUTPUT_STEPS = ( (BuiltinContextCreation, "context_creation"), (BuiltinModuleLookup, "module_lookup"), @@ -135,33 +137,40 @@ async def _resolve_parts( self, output: dict[str, Any], fields: tuple[tuple[str, dict[str, Any] | None], ...], identity: Identity ) -> list[Part]: artifacts: list[HostedArtifact] = [] - unique_ids: set[str] = set() + resolved: dict[str, HostedArtifact | None] = {} for field, reference_schema in fields: value = output.get(field) - reference = ( - parse_artifact_reference(value, reference_schema) - if reference_schema is not None and parse_artifact_reference is not None - else None - ) - if reference_schema is not None and reference is None: - continue + reference = None + if reference_schema is not None: + if ArtifactRef is None or not isinstance(value, dict): + continue + try: + if not validate_schema_dict(value, reference_schema).valid: + continue + reference = ArtifactRef.model_validate(value) + except (SchemaParseError, ValidationError): + continue artifact_id = reference.id if reference is not None else value - if not isinstance(artifact_id, str) or not _OPAQUE_ID.fullmatch(artifact_id) or artifact_id in unique_ids: + if not isinstance(artifact_id, str) or not _OPAQUE_ID.fullmatch(artifact_id): continue - try: - metadata = await self._resolve(artifact_id, identity) - except Exception: - continue # Do not expose resolver errors or signed URLs in task diagnostics. - if not isinstance(metadata, HostedArtifact): + if artifact_id not in resolved: + try: + metadata = await self._resolve(artifact_id, identity) + except Exception: + metadata = None # Keep resolver errors and URLs out of diagnostics. + resolved[artifact_id] = ( + metadata if isinstance(metadata, HostedArtifact) and self._is_allowed(metadata) else None + ) + metadata = resolved[artifact_id] + if metadata is None: continue if reference is not None and (metadata.media_type, metadata.size_bytes) != ( reference.media_type, reference.size_bytes, ): continue - if self._is_allowed(metadata): - unique_ids.add(artifact_id) - artifacts.append(metadata) + resolved[artifact_id] = None + artifacts.append(metadata) return [ Part(url=artifact.url, media_type=artifact.media_type, filename=artifact.filename) @@ -181,13 +190,20 @@ def _link_fields(schema: Any) -> tuple[tuple[str, dict[str, Any] | None], ...]: for name, declaration in properties.items(): if not isinstance(declaration, dict) or declaration.get("x-a2a-artifact") is not True: continue - if is_direct_artifact_reference is not None and is_direct_artifact_reference(schema, declaration): - fields.append((name, declaration)) - elif ( - declaration.get("type") == "string" - and not declaration.get("x-sensitive") - and _SCHEMA_APPLICATORS.isdisjoint(declaration) - ): + if declaration.get("x-sensitive"): + continue + if not _REFERENCE_ASSERTIONS.isdisjoint(declaration): + if ( + ArtifactRef is not None + and "$recursiveRef" not in schema + and "dependencies" not in schema + and declaration.get("type") in (None, "object") + and all( + key in _REFERENCE_FIELDS or (isinstance(key, str) and key.startswith("x-")) for key in declaration + ) + ): + fields.append((name, declaration)) + elif declaration.get("type") == "string" and _SCHEMA_APPLICATORS.isdisjoint(declaration): fields.append((name, None)) return tuple(fields) diff --git a/a2a/python/src/apcore_a2a/server/executor.py b/a2a/python/src/apcore_a2a/server/executor.py index 0bc2fcdc..0c53bd7a 100644 --- a/a2a/python/src/apcore_a2a/server/executor.py +++ b/a2a/python/src/apcore_a2a/server/executor.py @@ -359,7 +359,8 @@ async def _execute(self, context: RequestContext, event_queue: EventQueue, run: self._notify("working", "rejected") await self._reject(context, event_queue, self._failure_text(exc)) else: - logger.exception("Execution failed for task %s skill %s", context.task_id, skill_id) + if code != "POLICY_EVALUATION_ERROR": + logger.exception("Execution failed for task %s skill %s", context.task_id, skill_id) self._notify("working", "failed") await self._fail(context, event_queue, self._failure_text(exc)) diff --git a/a2a/python/tests/conformance/test_error_mapping.py b/a2a/python/tests/conformance/test_error_mapping.py index d89d7309..4bd6cc9d 100644 --- a/a2a/python/tests/conformance/test_error_mapping.py +++ b/a2a/python/tests/conformance/test_error_mapping.py @@ -23,6 +23,8 @@ "ModuleNotFoundError": ErrorCodes.MODULE_NOT_FOUND, "SchemaValidationError": ErrorCodes.SCHEMA_VALIDATION_ERROR, "ACLDeniedError": ErrorCodes.ACL_DENIED, + "PolicyDeniedError": ErrorCodes.POLICY_DENIED, + "PolicyEvaluationError": ErrorCodes.POLICY_EVALUATION_ERROR, "ApprovalDeniedError": ErrorCodes.APPROVAL_DENIED, "ApprovalTimeoutError": ErrorCodes.APPROVAL_TIMEOUT, "ApprovalPendingError": ErrorCodes.APPROVAL_PENDING, @@ -62,7 +64,9 @@ def _build_exception(spec: dict[str, Any]) -> Exception: ids=[c["id"] for c in _MAPPER_CASES], ) def test_error_mapping(case: dict[str, Any]) -> None: - rpc = ErrorMapper().to_jsonrpc_error(_build_exception(case["input"])) + rpc = ErrorMapper(disclose_refusal_reason=case.get("disclose_refusal_reason", False)).to_jsonrpc_error( + _build_exception(case["input"]) + ) assert rpc["code"] == case["expected_error_code"], f"[{case['id']}] code: got {rpc}" for needle in case.get("expected_error_message", []): assert needle in rpc["message"], f"[{case['id']}] missing {needle!r} in {rpc['message']!r}" diff --git a/a2a/python/tests/server/test_artifact_links.py b/a2a/python/tests/server/test_artifact_links.py index a1a47148..826473ce 100644 --- a/a2a/python/tests/server/test_artifact_links.py +++ b/a2a/python/tests/server/test_artifact_links.py @@ -13,6 +13,7 @@ from starlette.testclient import TestClient from apcore_a2a import A2AServerFactory, ArtifactLinkPolicy, HostedArtifact +from apcore_a2a.artifacts import _link_fields _SKILL = "artifact.download" _ALLOWED_URL = "https://downloads.example.test/signed?id=token" @@ -23,6 +24,40 @@ class _Result(BaseModel): sensitive: Annotated[str, Field(json_schema_extra={"x-a2a-artifact": True, "x-sensitive": True})] +def test_reference_assertion_never_falls_back_to_a_legacy_link() -> None: + schema = { + "type": "object", + "properties": { + "artifact": {"type": "string", "x-artifact-ref": True, "x-a2a-artifact": True}, + }, + } + + assert _link_fields(schema) == () + + +@pytest.mark.asyncio +@pytest.mark.parametrize("allowed", [True, False]) +async def test_duplicate_references_use_one_authorized_lookup(allowed: bool) -> None: + observed: list[str] = [] + + async def resolve(artifact_id: str, identity: Identity) -> HostedArtifact | None: + assert identity.id == "alice" + observed.append(artifact_id) + if allowed: + return HostedArtifact(_ALLOWED_URL, "report.txt", "text/plain", 4, time.time() + 30) + return None + + field = {"x-artifact-ref": True, "x-a2a-artifact": True} + fields = _link_fields({"type": "object", "properties": {"first": field, "second": field}}) + output = { + "first": {"id": "report", "media_type": "text/csv", "size_bytes": 4}, + "second": {"id": "report", "media_type": "text/plain", "size_bytes": 4}, + } + policy = ArtifactLinkPolicy(resolve, {"downloads.example.test"}) + assert len(await policy._resolve_parts(output, fields, Identity(id="alice"))) == int(allowed) + assert observed == ["report"] + + class _Authenticator: def authenticate(self, headers: dict[str, str]) -> Identity | None: token = headers.get("authorization", "").removeprefix("Bearer ") diff --git a/a2a/python/tests/server/test_executor.py b/a2a/python/tests/server/test_executor.py index 38495b35..fae6825a 100644 --- a/a2a/python/tests/server/test_executor.py +++ b/a2a/python/tests/server/test_executor.py @@ -747,6 +747,18 @@ async def test_execute_approval_pending_stays_a_resumable_pause(apcore_executor, assert "approval_id=7f3c1e" in text, "the message must reach the caller verbatim" +@pytest.mark.parametrize( + ("code", "state", "message"), + [ + (ErrorCodes.POLICY_DENIED, TaskState.TASK_STATE_REJECTED, "Access denied"), + (ErrorCodes.POLICY_EVALUATION_ERROR, TaskState.TASK_STATE_FAILED, "Policy evaluation failed"), + ], +) +async def test_policy_outcomes_have_distinct_task_states(apcore_executor, mock_executor, code, state, message): + error = ModuleError(code=code, message="internal rule detail", ai_guidance="private guidance") + assert await _terminal_status(apcore_executor, mock_executor, error, state) == message + + async def test_execute_internal_error_yields_fixed_message(apcore_executor, mock_executor): """srs FR-ERR-004 / FR-ERR-008: internal and unrecognized errors stay fixed.""" err = ModuleError( diff --git a/a2a/rust/Cargo.toml b/a2a/rust/Cargo.toml index fa166917..d3ef3b0c 100644 --- a/a2a/rust/Cargo.toml +++ b/a2a/rust/Cargo.toml @@ -9,7 +9,7 @@ readme = "README.md" authors = ["aiperceivable "] homepage = "https://aiperceivable.com" repository = "https://github.com/aiperceivable/apcore-surfaces" -documentation = "https://apcore.aiperceivable.com/" +documentation = "https://aiperceivable.github.io/apcore-surfaces/a2a/" keywords = ["ai", "a2a", "agent", "apcore", "protocol"] categories = ["api-bindings", "asynchronous", "web-programming"] diff --git a/a2a/rust/src/adapters/errors.rs b/a2a/rust/src/adapters/errors.rs index d3862065..f284f7f9 100644 --- a/a2a/rust/src/adapters/errors.rs +++ b/a2a/rust/src/adapters/errors.rs @@ -58,6 +58,23 @@ impl ErrorMapper { error: &ModuleError, disclose_refusal_reason: bool, ) -> JsonRpcError { + // Policy outcomes always use fixed text, including when ACL and + // approval refusal reasons are configured for disclosure. + match error.code { + ApcoreErrorCode::PolicyDenied => { + return JsonRpcError { + code: CODE_ACCESS_DENIED, + message: "Access denied".to_string(), + }; + } + ApcoreErrorCode::PolicyEvaluationError => { + return JsonRpcError { + code: CODE_INTERNAL_ERROR, + message: "Policy evaluation failed".to_string(), + }; + } + _ => (), + } // Log the full, unsanitized error server-side for diagnostics before any // sanitization (matches Python's `logger.error(..., exc_info=True)`). tracing::error!(error = ?error, "apcore error mapped to A2A JSON-RPC error"); @@ -149,6 +166,17 @@ impl ErrorMapper { } } +/// Whether a task ended because governance refused the invocation. +pub(crate) fn is_governance_refusal(code: ApcoreErrorCode) -> bool { + matches!( + code, + ApcoreErrorCode::ACLDenied + | ApcoreErrorCode::ApprovalDenied + | ApcoreErrorCode::ApprovalTimeout + | ApcoreErrorCode::PolicyDenied + ) +} + /// Whether [`ErrorMapper::to_jsonrpc_error`] lets this code's own message reach /// the caller (sanitized), or replaces it with a fixed per-class string. /// diff --git a/a2a/rust/src/artifacts.rs b/a2a/rust/src/artifacts.rs index 959a5548..ae45f5e6 100644 --- a/a2a/rust/src/artifacts.rs +++ b/a2a/rust/src/artifacts.rs @@ -1,10 +1,11 @@ //! Opt-in hosted download links for finalized A2A results. -use std::collections::HashSet; +use std::collections::{hash_map::Entry, HashMap, HashSet}; use std::sync::{Arc, LazyLock}; use std::time::{SystemTime, UNIX_EPOCH}; -use apcore::Identity; +use apcore::{ArtifactRef, Identity, SchemaValidator}; +use apcore_toolkit::schema_utils::artifact_fields; use async_trait::async_trait; use regex::Regex; use reqwest::Url; @@ -13,21 +14,6 @@ use serde_json::{Map, Value}; use crate::types::Part; const DEFAULT_MAX_BYTES: u64 = 8_388_608; -const SCHEMA_APPLICATORS: [&str; 12] = [ - "$ref", - "$dynamicRef", - "$recursiveRef", - "allOf", - "anyOf", - "oneOf", - "if", - "then", - "else", - "dependentSchemas", - "dependencies", - "patternProperties", -]; - static HOST: LazyLock = LazyLock::new(|| { Regex::new( r"\A[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\z", @@ -172,58 +158,75 @@ impl ArtifactLinkPolicy { pub(crate) async fn resolve_parts( &self, output: &Map, - fields: &[String], + fields: &[(String, Option)], identity: &Identity, ) -> Vec { - let mut seen = HashSet::new(); - let mut artifacts = Vec::new(); - for field in fields { - let Some(artifact_id) = output.get(field).and_then(Value::as_str) else { + let mut resolved = HashMap::new(); + let mut parts = Vec::new(); + let validator = SchemaValidator::new(); + for (field, schema) in fields { + let Some(value) = output.get(field) else { continue; }; - if OPAQUE_ID.is_match(artifact_id) && seen.insert(artifact_id) { - // Keep signed URLs and resolver errors out of task diagnostics. - if let Ok(Some(artifact)) = self.resolver.resolve(artifact_id, identity).await { - artifacts.push(artifact); + let reference = match schema { + Some(schema) if validator.validate(value, schema).valid => { + let Ok(reference) = serde_json::from_value::(value.clone()) else { + continue; + }; + Some(reference) + } + Some(_) => continue, + None => None, + }; + let Some(artifact_id) = reference + .as_ref() + .map(|r| r.id.as_str()) + .or_else(|| value.as_str()) + else { + continue; + }; + if !OPAQUE_ID.is_match(artifact_id) { + continue; + } + let candidate = match resolved.entry(artifact_id.to_owned()) { + Entry::Occupied(entry) => entry.into_mut(), + Entry::Vacant(entry) => { + // Keep signed URLs and resolver errors out of task diagnostics. + let artifact = self + .resolver + .resolve(artifact_id, identity) + .await + .ok() + .flatten() + .filter(|artifact| self.is_allowed(artifact)); + entry.insert(artifact) } + }; + let Some(artifact) = candidate.as_ref() else { + continue; + }; + if reference.as_ref().is_some_and(|reference| { + artifact.size_bytes != reference.size_bytes + || artifact.media_type != reference.media_type + }) { + continue; + } + if let Some(artifact) = candidate.take() { + parts.push(Part::HostedFileUrl { + url: artifact.url, + filename: artifact.filename, + media_type: artifact.media_type, + }); } } - artifacts - .into_iter() - .filter(|artifact| self.is_allowed(artifact)) - .map(|artifact| Part::HostedFileUrl { - url: artifact.url, - filename: artifact.filename, - media_type: artifact.media_type, - }) - .collect() + parts } } -fn direct_schema(schema: &Value, schema_type: &str) -> bool { - let Some(fields) = schema.as_object() else { - return false; - }; - fields.get("type").and_then(Value::as_str) == Some(schema_type) - && matches!(fields.get("x-sensitive"), None | Some(Value::Bool(false))) - && SCHEMA_APPLICATORS - .iter() - .all(|key| !fields.contains_key(*key)) -} - -pub(crate) fn link_fields(schema: &Value) -> Vec { - if !direct_schema(schema, "object") { - return Vec::new(); - } - schema["properties"] - .as_object() +pub(crate) fn link_fields(schema: &Value) -> Vec<(String, Option)> { + artifact_fields(schema, "x-a2a-artifact") .into_iter() - .flatten() - .filter(|(_, declaration)| { - direct_schema(declaration, "string") - && declaration["x-a2a-artifact"] == Value::Bool(true) - }) - .map(|(name, _)| name.clone()) + .map(|(name, reference)| (name.to_owned(), reference.cloned())) .collect() } @@ -311,8 +314,84 @@ mod tests { "nested": {"type": "object", "properties": {"id": {"type": "string", "x-a2a-artifact": true}}} } }); - assert_eq!(link_fields(&schema), ["eligible"]); + assert_eq!(link_fields(&schema), [("eligible".into(), None)]); schema["allOf"] = json!([]); assert!(link_fields(&schema).is_empty()); } + + #[tokio::test] + async fn core_artifact_references_match_the_authorized_metadata() { + use std::sync::atomic::{AtomicUsize, Ordering}; + + #[derive(Default)] + struct Hosted(AtomicUsize); + + #[async_trait] + impl ArtifactResolver for Hosted { + async fn resolve( + &self, + id: &str, + identity: &Identity, + ) -> Result, Box> + { + assert_eq!(id, "report-id"); + self.0.fetch_add(1, Ordering::Relaxed); + Ok((identity.id() == "owner").then(|| HostedArtifact { + url: "https://downloads.example/report".into(), + filename: "report.txt".into(), + media_type: "text/plain".into(), + size_bytes: 3, + expires_at: f64::from(u32::MAX), + })) + } + } + + let hosted = Arc::new(Hosted::default()); + let policy = ArtifactLinkPolicy::new(hosted.clone(), ["downloads.example"]).unwrap(); + let schema = json!({"type": "object", "properties": { + "artifact": {"x-a2a-artifact": true, "x-artifact-ref": true, "x-max-bytes": 3}, + "ambiguous": {"type":"string", "x-a2a-artifact": true, "x-artifact-ref": true} + }}); + let fields = link_fields(&schema); + let owner = Identity::new("owner".into(), "user".into(), vec![], Default::default()); + for (value, count) in [ + ( + json!({"id":"report-id","media_type":"text/plain","size_bytes":3}), + 1, + ), + ( + json!({"id":"report-id","media_type":"text/csv","size_bytes":3}), + 0, + ), + ( + json!({"id":"report-id","media_type":"text/plain","size_bytes":4}), + 0, + ), + (json!("report-id"), 0), + ] { + let output = json!({"artifact": value, "ambiguous": "report-id"}); + assert_eq!( + policy + .resolve_parts(output.as_object().unwrap(), &fields, &owner) + .await + .len(), + count, + ); + } + let mut duplicate_fields = fields; + duplicate_fields.push(("another".into(), duplicate_fields[0].1.clone())); + let output = json!({ + "artifact": {"id":"report-id","media_type":"text/csv","size_bytes":3}, + "another": {"id":"report-id","media_type":"text/plain","size_bytes":3} + }); + let lookups = hosted.0.load(Ordering::Relaxed); + assert_eq!( + policy + .resolve_parts(output.as_object().unwrap(), &duplicate_fields, &owner) + .await + .len(), + 1, + ); + assert_eq!(hosted.0.load(Ordering::Relaxed), lookups + 1); + } } diff --git a/a2a/rust/src/server/handlers.rs b/a2a/rust/src/server/handlers.rs index 807e036a..393ec7ce 100644 --- a/a2a/rust/src/server/handlers.rs +++ b/a2a/rust/src/server/handlers.rs @@ -460,12 +460,10 @@ fn error_to_status(err: &ModuleError, disclose_refusal_reason: bool) -> TaskStat // A2A 1.0 defines `rejected` as a terminal state, and a policy refusal // is what it describes (srs FR-ERR-012). `failed` said only "something // broke", which for a refusal is both wrong and an invitation to retry. - ErrorCode::ACLDenied | ErrorCode::ApprovalDenied | ErrorCode::ApprovalTimeout => { - TaskStatus::with_message( - TaskState::Rejected, - Message::agent_text(failure_text(err, disclose_refusal_reason)), - ) - } + code if crate::adapters::errors::is_governance_refusal(code) => TaskStatus::with_message( + TaskState::Rejected, + Message::agent_text(failure_text(err, disclose_refusal_reason)), + ), _ => TaskStatus::with_message( TaskState::Failed, Message::agent_text(failure_text(err, disclose_refusal_reason)), @@ -1850,6 +1848,28 @@ mod tests { ); } + #[test] + fn policy_outcomes_have_distinct_task_states() { + for (code, state, message) in [ + ( + ErrorCode::PolicyDenied, + TaskState::Rejected, + "Access denied", + ), + ( + ErrorCode::PolicyEvaluationError, + TaskState::Failed, + "Policy evaluation failed", + ), + ] { + let err = + ModuleError::new(code, "internal rule detail").with_ai_guidance("private guidance"); + let status = error_to_status(&err, true); + assert_eq!(status.state, state); + assert_eq!(status_text(&status).as_deref(), Some(message)); + } + } + #[test] fn disclose_refusal_reason_reaches_the_task_status_surface() { // The flag must move both surfaces together, or the JSON-RPC error and diff --git a/a2a/rust/tests/conformance.rs b/a2a/rust/tests/conformance.rs index 37821c52..564137bb 100644 --- a/a2a/rust/tests/conformance.rs +++ b/a2a/rust/tests/conformance.rs @@ -367,6 +367,14 @@ fn conformance_error_mapping() { ErrorCode::ACLDenied, format!("caller {} module {}", spec["caller"], spec["module"]), ), + "PolicyDeniedError" | "PolicyEvaluationError" => ( + if name == "PolicyDeniedError" { + ErrorCode::PolicyDenied + } else { + ErrorCode::PolicyEvaluationError + }, + spec["message"].as_str().unwrap_or_default().to_string(), + ), "ApprovalDeniedError" => ( ErrorCode::ApprovalDenied, spec["message"].as_str().unwrap_or("denied").to_string(), @@ -394,7 +402,10 @@ fn conformance_error_mapping() { .collect(), ); } - let rpc = ErrorMapper::to_jsonrpc_error(&err); + let rpc = ErrorMapper::to_jsonrpc_error_with( + &err, + case["disclose_refusal_reason"].as_bool().unwrap_or(false), + ); assert_eq!( rpc.code, case["expected_error_code"].as_i64().unwrap() as i32, diff --git a/a2a/typescript/src/adapters/errors.ts b/a2a/typescript/src/adapters/errors.ts index 0394c82f..ddd7ac3b 100644 --- a/a2a/typescript/src/adapters/errors.ts +++ b/a2a/typescript/src/adapters/errors.ts @@ -41,9 +41,9 @@ const GOVERNANCE_REFUSALS: ReadonlyMap Promise; +// A null reference denotes a separately declared legacy opaque ID. +type ArtifactCandidates = Map; + /** Opt in to hosted links without downloading their contents. */ export class ArtifactLinkPolicy { private readonly allowedHosts: ReadonlySet; @@ -65,14 +72,22 @@ export class ArtifactLinkPolicy { } /** @internal */ - async resolveDownloads(ids: readonly string[], identity: Identity, isActive: () => boolean): Promise { + async resolveDownloads( + ids: readonly string[], + identity: Identity, + isActive: () => boolean, + references?: ReadonlyMap, + ): Promise { const downloads: HostedArtifact[] = []; for (const id of ids) { if (!isActive()) return []; + const declarations = references?.get(id); try { const metadata = await this.resolve(id, identity); if (metadata === null || typeof metadata !== "object") continue; const { url, filename, mediaType, sizeBytes, expiresAt } = metadata; + if (declarations && !declarations.some((reference) => reference === null || + (reference.media_type === mediaType && reference.size_bytes === sizeBytes))) continue; const download = { url, filename, mediaType, sizeBytes, expiresAt }; if (this.allows(download)) downloads.push(download); } catch { @@ -112,11 +127,21 @@ function unambiguous(schema: Record): boolean { return !schema["x-sensitive"] && !SCHEMA_APPLICATORS.some((key) => Object.hasOwn(schema, key)); } -function linkFields(schema: Record): string[] { +function linkFields(schema: Record): Array<{ name: string; canonical: boolean }> { if (schema.type !== "object" || !unambiguous(schema) || !isRecord(schema.properties)) return []; - return Object.entries(schema.properties).filter(([, field]) => - isRecord(field) && field.type === "string" && field["x-a2a-artifact"] === true && unambiguous(field) - ).map(([name]) => name); + const fields = []; + for (const [name, field] of Object.entries(schema.properties)) { + if (!isRecord(field) || field["x-a2a-artifact"] !== true || !unambiguous(field)) continue; + if (ARTIFACT_ASSERTIONS.some((key) => Object.hasOwn(field, key))) { + if (typeof apcore.parseArtifactRef === "function" && (field.type === undefined || field.type === "object") && + Object.keys(field).every((key) => key === "type" || key === "title" || key === "description" || key.startsWith("x-"))) { + fields.push({ name, canonical: true }); + } + } else if (field.type === "string") { + fields.push({ name, canonical: false }); + } + } + return fields; } function snapshotIdentity(identity: Identity): Identity { @@ -151,18 +176,23 @@ export function captureArtifactDeclaration(registry: unknown, executor: unknown, const schema = jsonSchemaToTypeBox(declaration.schema); const principal = snapshotIdentity(identity); - function ids(output: Record): string[] { - if (!schemaValidator.validate(output, schema).valid) return []; - const unique = new Set(); - for (const field of fields) { - if (!Object.hasOwn(output, field)) continue; - const value = output[field]; - if (typeof value === "string" && ARTIFACT_ID.test(value)) unique.add(value); + function candidates(output: Record): ArtifactCandidates { + const found: ArtifactCandidates = new Map(); + if (!schemaValidator.validate(output, schema).valid) return found; + for (const { name, canonical } of fields) { + if (!Object.hasOwn(output, name)) continue; + const value = output[name]; + const reference = canonical ? apcore.parseArtifactRef(value) : null; + const id = reference?.id ?? value; + if (typeof id !== "string" || !ARTIFACT_ID.test(id)) continue; + const declarations = found.get(id); + if (declarations) declarations.push(reference); + else found.set(id, [reference]); } - return [...unique]; + return found; } - return { executor, strategy, principal, declaration, stepNames, ids }; + return { executor, strategy, principal, declaration, stepNames, candidates }; } catch { return null; } @@ -186,12 +216,11 @@ export async function hostedArtifactParts( } if (!trace.success || next !== capture.stepNames.length || !capture.declaration.isCurrent()) return []; try { - const ids = capture.ids(output); - if (!ids.length) return []; - const downloads = await policy.resolveDownloads(ids, capture.principal, isActive); + const candidates = capture.candidates(output); + if (!candidates.size) return []; + const downloads = await policy.resolveDownloads([...candidates.keys()], capture.principal, isActive, candidates); if (!downloads.length || !isActive() || !capture.declaration.isCurrent()) return []; - const finalIds = capture.ids(output); - if (finalIds.length !== ids.length || ids.some((id, index) => finalIds[index] !== id)) return []; + if (JSON.stringify([...capture.candidates(output)]) !== JSON.stringify([...candidates])) return []; const now = Date.now() / 1000; return downloads.filter(({ expiresAt }) => expiresAt > now).map(({ url, filename, mediaType }) => Part.fromJSON({ url, filename, mediaType })); diff --git a/a2a/typescript/src/server/executor.ts b/a2a/typescript/src/server/executor.ts index e3f3a5b9..818c5735 100644 --- a/a2a/typescript/src/server/executor.ts +++ b/a2a/typescript/src/server/executor.ts @@ -324,7 +324,9 @@ export class ApCoreAgentExecutor implements AgentExecutor { this.publishOutcome(task, eventBus, "working", "rejected", failureText(e, this.errorMapper)); return; } - console.error(`Execution failed for task ${taskId} skill ${skillId}:`, e); + if (code !== "POLICY_EVALUATION_ERROR") { + console.error(`Execution failed for task ${taskId} skill ${skillId}:`, e); + } this.publishOutcome(task, eventBus, "working", "failed", failureText(e, this.errorMapper)); } } diff --git a/a2a/typescript/tests/conformance/error-mapping.test.ts b/a2a/typescript/tests/conformance/error-mapping.test.ts index fa31fe9e..29d64333 100644 --- a/a2a/typescript/tests/conformance/error-mapping.test.ts +++ b/a2a/typescript/tests/conformance/error-mapping.test.ts @@ -10,6 +10,8 @@ const codeByName: Record = { ModuleNotFoundError: ErrorCodes.MODULE_NOT_FOUND, SchemaValidationError: ErrorCodes.SCHEMA_VALIDATION_ERROR, ACLDeniedError: ErrorCodes.ACL_DENIED, + PolicyDeniedError: ErrorCodes.POLICY_DENIED, + PolicyEvaluationError: ErrorCodes.POLICY_EVALUATION_ERROR, ApprovalDeniedError: ErrorCodes.APPROVAL_DENIED, ApprovalTimeoutError: ErrorCodes.APPROVAL_TIMEOUT, ApprovalPendingError: ErrorCodes.APPROVAL_PENDING, @@ -45,7 +47,7 @@ function buildError(spec: any): unknown { (e: { surface?: string }) => e.surface !== "server", )) { it(c.id, () => { - const rpc = new ErrorMapper().toJsonRpcError(buildError(c.input)); + const rpc = new ErrorMapper(c.disclose_refusal_reason ?? false).toJsonRpcError(buildError(c.input)); expect(rpc.code).toBe(c.expected_error_code); for (const needle of c.expected_error_message ?? []) expect(rpc.message).toContain(needle); for (const forbidden of c.expected_message_excludes ?? []) expect(rpc.message).not.toContain(forbidden); diff --git a/a2a/typescript/tests/server/artifact-links.test.ts b/a2a/typescript/tests/server/artifact-links.test.ts index 748f4f36..c3b82861 100644 --- a/a2a/typescript/tests/server/artifact-links.test.ts +++ b/a2a/typescript/tests/server/artifact-links.test.ts @@ -88,6 +88,87 @@ describe("hosted artifact links", () => { expect(resolve).toHaveBeenCalledTimes(1); }); + it.each([ + { sizeBytes: 4, mediaType: "text/plain", linked: true }, + { sizeBytes: 5, mediaType: "text/plain", linked: false }, + { sizeBytes: 4, mediaType: "image/png", linked: false }, + ])("projects a canonical reference only when resolver metadata matches (%j)", async ({ sizeBytes, mediaType, linked }) => { + const registry = new Registry(); + const data = { primary: { id: "initial", media_type: "text/plain", size_bytes: 4 } }; + await registry.register(skill, { + ...downloadModule(), + outputSchema: { + type: "object", + properties: { primary: { + type: "object", "x-artifact-ref": true, "x-a2a-artifact": true, + "x-media-types": ["text/plain"], "x-max-bytes": 8, + } }, + required: ["primary"], + }, + execute: () => data, + }); + const resolve = vi.fn(async () => ({ ...artifact(), sizeBytes, mediaType })); + const executor = new Executor({ registry }); + const artifactLinks = new ArtifactLinkPolicy(resolve, [host]); + // Verify the captured declaration also survives Core's first-use schema compilation. + const task = await send(executor, { auth, artifactLinks }); + const second = await send(executor, { auth, artifactLinks }); + const parts = [{ data }, ...(linked ? [{ url, filename: "report.txt", mediaType }] : [])]; + expect(task.artifacts[0].parts).toEqual(parts); + expect(second.artifacts[0].parts).toEqual(parts); + expect(resolve).toHaveBeenCalledTimes(2); + expect(resolve).toHaveBeenCalledWith("initial", expect.objectContaining({ id: "alice" })); + }); + + it.each(["legacy", "over-limit", "ambiguous", "stale"])("withholds a canonical link after %s", async (scenario) => { + const registry = new Registry(); + const data = { primary: { id: "initial", media_type: "text/plain", size_bytes: 4 } }; + const module = { + ...downloadModule(), + outputSchema: { + type: "object", + properties: { primary: { "x-artifact-ref": true, "x-a2a-artifact": true, "x-max-bytes": 8 } }, + ...(scenario === "ambiguous" ? { allOf: [{}] } : {}), + }, + execute: () => data, + }; + await registry.register(skill, module); + const finalData = scenario === "legacy" ? { primary: "initial" } : scenario === "over-limit" + ? { primary: { ...data.primary, size_bytes: 9 } } : data; + class FinalOutput extends Middleware { + override after() { return finalData; } + } + const resolve = vi.fn(async () => { + if (scenario === "stale") { + await registry.unregister(skill); + await registry.register(skill, module); + } + return { ...artifact(), sizeBytes: scenario === "over-limit" ? 9 : 4 }; + }); + const task = await send(new Executor({ registry }).use(new FinalOutput()), { + auth, artifactLinks: new ArtifactLinkPolicy(resolve, [host]), + }); + expect(task.artifacts[0].parts).toEqual([{ data: finalData }]); + expect(resolve).toHaveBeenCalledTimes(scenario === "stale" ? 1 : 0); + }); + + it.each([false, true])("resolves duplicate canonical IDs once and uses the matching declaration (denied %s)", async (denied) => { + const registry = new Registry(); + const field = { type: "object", "x-artifact-ref": true, "x-a2a-artifact": true }; + const primary = { id: "initial", media_type: "text/plain", size_bytes: 5 }; + const data = { primary, duplicate: { ...primary, size_bytes: 4 } }; + await registry.register(skill, { + ...downloadModule(), + outputSchema: { type: "object", properties: { primary: field, duplicate: { ...field } } }, + execute: () => data, + }); + const resolve = vi.fn(async () => denied ? null : artifact()); + const task = await send(new Executor({ registry }), { auth, artifactLinks: new ArtifactLinkPolicy(resolve, [host]) }); + const links = denied ? [] : [{ url, filename: "report.txt", mediaType: "text/plain" }]; + expect(task.artifacts[0].parts).toEqual([{ data }, ...links]); + expect(resolve).toHaveBeenCalledTimes(1); + }); + it("withholds links for invalid replacements and recovered execution failures", async () => { const registry = new Registry(); const resolve = vi.fn(async () => artifact()); diff --git a/a2a/typescript/tests/server/executor.test.ts b/a2a/typescript/tests/server/executor.test.ts index cb3f0fb6..198b6971 100644 --- a/a2a/typescript/tests/server/executor.test.ts +++ b/a2a/typescript/tests/server/executor.test.ts @@ -534,6 +534,16 @@ describe("failed-task error classification", () => { expect(text).toContain("approvalId=7f3c1e"); }); + it.each([ + [ErrorCodes.POLICY_DENIED, TaskState.TASK_STATE_REJECTED, "Access denied"], + [ErrorCodes.POLICY_EVALUATION_ERROR, TaskState.TASK_STATE_FAILED, "Policy evaluation failed"], + ])("maps %s to its task state without disclosing policy details", async (code, state, message) => { + const error = Object.assign(new ModuleError(code, "internal rule detail"), { + aiGuidance: "private guidance", + }); + expect(await terminalText(error, state, { discloseRefusalReason: true })).toBe(message); + }); + it("carries the reason onto the task status when disclosure is enabled", async () => { // srs FR-ERR-011: the flag must move both surfaces together, or the // JSON-RPC error and the task status would disagree about the same refusal. diff --git a/cli/README.md b/cli/README.md index 7daf808b..3e8a5280 100644 --- a/cli/README.md +++ b/cli/README.md @@ -498,7 +498,8 @@ Schema-generated flags (e.g. `--a`, `--b`) are added automatically from the modu | `46` | Approval denied or timed out | | `47` | Configuration error | | `48` | Schema circular reference | -| `77` | ACL denied | +| `75` | Policy evaluation failed (retryable) | +| `77` | ACL or policy denied | | `130` | Execution cancelled (Ctrl+C) | --- diff --git a/cli/docs/features/config-resolver.md b/cli/docs/features/config-resolver.md index a9ecf979..781d181d 100644 --- a/cli/docs/features/config-resolver.md +++ b/cli/docs/features/config-resolver.md @@ -158,8 +158,8 @@ extensions: root: /custom/path auth: api_key: "keyring:auth.api_key" -logging: - level: DEBUG +apcore-cli: + logging_level: DEBUG ``` Flattened to: @@ -167,7 +167,7 @@ Flattened to: { "extensions.root": "/custom/path", "auth.api_key": "keyring:auth.api_key", - "logging.level": "DEBUG", + "apcore-cli.logging_level": "DEBUG", } ``` diff --git a/cli/docs/features/core-dispatcher.md b/cli/docs/features/core-dispatcher.md index 4599aad4..a38a639e 100644 --- a/cli/docs/features/core-dispatcher.md +++ b/cli/docs/features/core-dispatcher.md @@ -411,9 +411,14 @@ Logic steps: | STDIN not object | 2 | "Error: STDIN JSON must be an object, got {type}." | FR-DISP-004 AF-3 | | Extensions dir missing | 47 | "Error: Extensions directory not found: '{path}'. Set APCORE_EXTENSIONS_ROOT or verify the path." | FR-DISP-003 AF-1 | | Extensions dir unreadable | 47 | "Error: Cannot read extensions directory: '{path}'. Check file permissions." | FR-DISP-003 AF-2 | +| Policy evaluation failed | 75 | "Policy evaluation failed" | apcore protocol §7.5 | +| Policy denied | 77 | "Policy denied the validated invocation" | apcore protocol §7.5 | | ACL denied | 77 | "Error: Permission denied for module '{id}'." | FR-DISP-002 AF-8 | | User interruption | 130 | "Execution cancelled." | FR-DISP-002 AF-6 | +Both policy outcomes use fixed CLI messages. JSON preserves the Core error +code and retryability and omits evaluator details and guidance. + --- ## 7. Verification diff --git a/cli/docs/getting-started.md b/cli/docs/getting-started.md index 2b5796b2..0c3602ab 100644 --- a/cli/docs/getting-started.md +++ b/cli/docs/getting-started.md @@ -187,8 +187,6 @@ The module ID (`greet.hello`) is derived from the directory structure — no reg # apcore.yaml extensions: root: ./extensions -logging: - level: DEBUG sandbox: enabled: false ``` @@ -199,6 +197,7 @@ sandbox: |----------|-------------|---------| | `APCORE_EXTENSIONS_ROOT` | Path to extensions directory | `./extensions` | | `APCORE_CLI_AUTO_APPROVE` | Set `1` to bypass approval prompts | *(unset)* | +| `APCORE_CLI_LOGGING_LEVEL` | CLI-specific log level. Overrides `APCORE_LOGGING_LEVEL`. | *(unset)* | | `APCORE_LOGGING_LEVEL` | Log level (`DEBUG`, `INFO`, `WARNING`, `ERROR`) | `WARNING` | For the full configuration reference, see the [Config Resolver spec](features/config-resolver.md). diff --git a/cli/docs/tech-design.md b/cli/docs/tech-design.md index 0c235580..d13f7ba3 100644 --- a/cli/docs/tech-design.md +++ b/cli/docs/tech-design.md @@ -1799,6 +1799,9 @@ setDocsUrl('https://docs.apcore.dev/cli'); **Class:** `ConfigResolver` **Purpose:** Resolve configuration values using the 4-tier precedence hierarchy. +The resolver accepts `logging.level` as a compatibility alias for +`apcore-cli.logging_level`. Standalone logging uses `--log-level`, +`APCORE_CLI_LOGGING_LEVEL`, and `APCORE_LOGGING_LEVEL` in that order. ```python class ConfigResolver: @@ -1889,6 +1892,8 @@ All exit codes aligned with apcore PROTOCOL_SPEC section 8. | `CONFIG_INVALID` | 47 | Config decryption failed | No | `"Error: Failed to decrypt configuration value '{key}'. Re-configure with 'apcore-cli config set {key}'."` | FR-SEC-002 AF-2 | | `MODULE_EXECUTE_ERROR` | 1 | Module returned error | Depends | `"Error: Module '{id}' execution failed: {detail}."` | FR-DISP-002 AF-4 | | `MODULE_TIMEOUT` | 1 | Module execution timeout | Yes | `"Error: Module '{id}' timed out after {timeout}s."` | — | +| `POLICY_EVALUATION_ERROR` | 75 | Policy evaluation failed | Yes | `"Policy evaluation failed"` | apcore protocol §7.5 | +| `POLICY_DENIED` | 77 | Validated invocation denied by policy | No | `"Policy denied the validated invocation"` | apcore protocol §7.5 | | `ACL_DENIED` | 77 | Permission denied by ACL | No | `"Error: Permission denied for module '{id}'."` | FR-DISP-002 AF-8, FR-SEC-001 AF-1/2 | | `EXECUTION_CANCELLED` | 130 | Ctrl+C / SIGINT | Yes | `"Execution cancelled."` | FR-DISP-002 AF-6 | diff --git a/cli/python/README.md b/cli/python/README.md index 63a1566e..da67c823 100644 --- a/cli/python/README.md +++ b/cli/python/README.md @@ -420,7 +420,8 @@ The `list` command gained several discovery filters in v0.6.0: `--search`, `--st | `46` | Approval denied or timed out | | `47` | Configuration error | | `48` | Schema circular reference | -| `77` | ACL denied | +| `75` | Policy evaluation failed (retryable) | +| `77` | ACL or policy denied | | `130` | Execution cancelled (Ctrl+C) | ## Configuration diff --git a/cli/python/pyproject.toml b/cli/python/pyproject.toml index 75261a2f..644dc41d 100644 --- a/cli/python/pyproject.toml +++ b/cli/python/pyproject.toml @@ -56,7 +56,7 @@ apcore-cli = "apcore_cli.__main__:main" [project.urls] Homepage = "https://aiperceivable.com" Repository = "https://github.com/aiperceivable/apcore-surfaces/tree/main/cli/python" -Documentation = "https://github.com/aiperceivable/apcore-cli-python#readme" +Documentation = "https://aiperceivable.github.io/apcore-surfaces/cli/" Issues = "https://github.com/aiperceivable/apcore-surfaces/issues" [tool.hatch.build.targets.wheel] diff --git a/cli/python/src/apcore_cli/__init__.py b/cli/python/src/apcore_cli/__init__.py index f655ed40..b319d94f 100644 --- a/cli/python/src/apcore_cli/__init__.py +++ b/cli/python/src/apcore_cli/__init__.py @@ -71,6 +71,7 @@ EXIT_MODULE_LOAD_ERROR, EXIT_MODULE_NOT_FOUND, EXIT_MODULE_TIMEOUT, + EXIT_POLICY_EVALUATION_ERROR, EXIT_SCHEMA_CIRCULAR_REF, EXIT_SCHEMA_VALIDATION_ERROR, EXIT_SIGINT, @@ -219,6 +220,7 @@ "EXIT_CONFIG_BIND_ERROR", "EXIT_CONFIG_MOUNT_ERROR", "EXIT_ERROR_FORMATTER_DUPLICATE", + "EXIT_POLICY_EVALUATION_ERROR", "EXIT_ACL_DENIED", "EXIT_CONFIG_NAMESPACE_RESERVED", "EXIT_CONFIG_NAMESPACE_DUPLICATE", diff --git a/cli/python/src/apcore_cli/exit_codes.py b/cli/python/src/apcore_cli/exit_codes.py index b8046869..0c36ce87 100644 --- a/cli/python/src/apcore_cli/exit_codes.py +++ b/cli/python/src/apcore_cli/exit_codes.py @@ -39,6 +39,7 @@ EXIT_CONFIG_BIND_ERROR = 65 EXIT_CONFIG_MOUNT_ERROR = 66 EXIT_ERROR_FORMATTER_DUPLICATE = 70 +EXIT_POLICY_EVALUATION_ERROR = 75 EXIT_ACL_DENIED = 77 # Both namespace errors share exit code 78 per protocol spec. EXIT_CONFIG_NAMESPACE_RESERVED = 78 @@ -87,6 +88,8 @@ "MODULE_EXECUTE_ERROR": EXIT_MODULE_EXECUTE_ERROR, "MODULE_TIMEOUT": EXIT_MODULE_TIMEOUT, "ACL_DENIED": EXIT_ACL_DENIED, + "POLICY_DENIED": EXIT_ACL_DENIED, + "POLICY_EVALUATION_ERROR": EXIT_POLICY_EVALUATION_ERROR, # FE-14 §6.1: a malformed ACL file is a *configuration* fault, not a # denial. 47 (CONFIG_INVALID) rather than 77 — 77 must stay reserved for # an actual access decision or scripts branching on it would misreport a diff --git a/cli/python/src/apcore_cli/module_errors.py b/cli/python/src/apcore_cli/module_errors.py index 10415e83..51f31b90 100644 --- a/cli/python/src/apcore_cli/module_errors.py +++ b/cli/python/src/apcore_cli/module_errors.py @@ -43,20 +43,35 @@ def resolve_error_stream(spec: ErrorStream) -> TextIO: return spec +def policy_error_diagnostic(error: BaseException) -> tuple[str, bool] | None: + """Return the public message and retryability for a Core policy outcome.""" + code = getattr(error, "code", None) + code = getattr(code, "value", code) + if code == "POLICY_DENIED": + return "Policy denied the validated invocation", False + if code == "POLICY_EVALUATION_ERROR": + return "Policy evaluation failed", True + return None + + def emit_error_json(e: BaseException, exit_code: int, file: TextIO | None = None) -> None: """Emit the single-line JSON error document (F3).""" dest = file or sys.stderr code = getattr(e, "code", None) + policy = policy_error_diagnostic(e) payload: dict[str, Any] = { "error": True, "code": code or "UNKNOWN", - "message": str(e), + "message": policy[0] if policy else str(e), "exit_code": exit_code, } - for field in ("details", "suggestion", "ai_guidance", "retryable", "user_fixable"): - val = getattr(e, field, None) - if val is not None: - payload[field] = val + if policy: + payload["retryable"] = policy[1] + else: + for field in ("details", "suggestion", "ai_guidance", "retryable", "user_fixable"): + val = getattr(e, field, None) + if val is not None: + payload[field] = val dest.write(json.dumps(payload, default=str) + "\n") dest.flush() @@ -65,20 +80,22 @@ def emit_error_tty(e: BaseException, exit_code: int, file: TextIO | None = None) """Emit the human-readable error with guidance fields (F3).""" dest = file or sys.stderr code = getattr(e, "code", None) - header = f"Error [{code}]: {e}" if code else f"Error: {e}" + policy = policy_error_diagnostic(e) + message = policy[0] if policy else str(e) + header = f"Error [{code}]: {message}" if code else f"Error: {message}" dest.write(header + "\n") - details = getattr(e, "details", None) + details = None if policy else getattr(e, "details", None) if details and isinstance(details, dict): dest.write("\n Details:\n") for k, v in details.items(): dest.write(f" {k}: {v}\n") - suggestion = getattr(e, "suggestion", None) + suggestion = None if policy else getattr(e, "suggestion", None) if suggestion: dest.write(f"\n Suggestion: {suggestion}\n") - retryable = getattr(e, "retryable", None) + retryable = policy[1] if policy else getattr(e, "retryable", None) if retryable is not None: label = "Yes" if retryable else "No (same input will fail again)" dest.write(f" Retryable: {label}\n") diff --git a/cli/python/src/apcore_cli/system_cmd.py b/cli/python/src/apcore_cli/system_cmd.py index ac38d45f..52c3b726 100644 --- a/cli/python/src/apcore_cli/system_cmd.py +++ b/cli/python/src/apcore_cli/system_cmd.py @@ -25,6 +25,7 @@ from apcore_cli.approval import check_approval from apcore_cli.exit import exit_with from apcore_cli.exit_codes import exit_code_for_error +from apcore_cli.module_errors import policy_error_diagnostic from apcore_cli.output import format_exec_result, resolve_format logger = logging.getLogger("apcore_cli.system_cmd") @@ -44,7 +45,9 @@ def _exit_on_system_error(e: Exception) -> NoReturn: error to exit 1. Mirrors Rust ``cli::map_module_error_to_exit_code`` and TS ``exitCodeForError``. """ - click.echo(f"Error: {e}", err=True) + policy = policy_error_diagnostic(e) + message = policy[0] if policy else str(e) + click.echo(f"Error: {message}", err=True) exit_with(exit_code_for_error(e)) diff --git a/cli/python/tests/test_exit_codes.py b/cli/python/tests/test_exit_codes.py index 55e4071f..9864f372 100644 --- a/cli/python/tests/test_exit_codes.py +++ b/cli/python/tests/test_exit_codes.py @@ -118,6 +118,12 @@ def test_real_apcore_acl_rule_error_maps_to_47(self) -> None: assert exit_code_for_error(ACLRuleError("bad rule")) == 47 + def test_policy_refusal_is_distinct_from_temporary_evaluation_failure(self) -> None: + from apcore.errors import PolicyDeniedError, PolicyEvaluationError + + assert exit_code_for_error(PolicyDeniedError()) == 77 + assert exit_code_for_error(PolicyEvaluationError()) == 75 + def test_cli_error_code_map_is_the_shared_map(self) -> None: """Two copies of a value set are two things that drift — cli.py's ``_ERROR_CODE_MAP`` and the fallback must be the same object.""" @@ -136,3 +142,33 @@ class _ApcoreLikeError(Exception): err = _ApcoreLikeError(code) err.code = code return err + + +def test_policy_diagnostics_mask_protected_message_and_guidance() -> None: + import json + from io import StringIO + + from apcore_cli.module_errors import emit_error_json, emit_error_tty + + for code, exit_code, message, retryable in ( + ("POLICY_DENIED", 77, "Policy denied the validated invocation", False), + ("POLICY_EVALUATION_ERROR", 75, "Policy evaluation failed", True), + ): + error = RuntimeError("private-policy") + error.code = code + error.details = {"rule": "private-policy"} + error.suggestion = "private-policy" + error.ai_guidance = "private-policy" + buffer = StringIO() + emit_error_json(error, exit_code, buffer) + assert json.loads(buffer.getvalue()) == { + "error": True, + "code": code, + "message": message, + "exit_code": exit_code, + "retryable": retryable, + } + buffer = StringIO() + emit_error_tty(error, exit_code, buffer) + assert message in buffer.getvalue() + assert "private-policy" not in buffer.getvalue() diff --git a/cli/rust/Cargo.toml b/cli/rust/Cargo.toml index f22770cd..78a36fef 100644 --- a/cli/rust/Cargo.toml +++ b/cli/rust/Cargo.toml @@ -8,7 +8,7 @@ readme = "README.md" authors = ["aiperceivable "] homepage = "https://aiperceivable.com" repository = "https://github.com/aiperceivable/apcore-surfaces" -documentation = "https://apcore.aiperceivable.com/" +documentation = "https://aiperceivable.github.io/apcore-surfaces/cli/" keywords = ["ai", "llm", "module", "cli", "schema"] categories = ["command-line-utilities", "api-bindings"] diff --git a/cli/rust/README.md b/cli/rust/README.md index 80d75199..77f4b169 100644 --- a/cli/rust/README.md +++ b/cli/rust/README.md @@ -343,7 +343,8 @@ fields neither source supplied. | `65` | `EXIT_CONFIG_BIND_ERROR` -- Configuration bind to struct failed (Config Bus) | | `66` | `EXIT_CONFIG_MOUNT_ERROR` -- Configuration namespace mount failed (Config Bus) | | `70` | `EXIT_ERROR_FORMATTER_DUPLICATE` -- Duplicate error formatter registration | -| `77` | ACL denied | +| `75` | `EXIT_POLICY_EVALUATION_ERROR` — Policy evaluation failed (retryable) | +| `77` | `EXIT_ACL_DENIED` — ACL or policy denied | | `78` | `EXIT_CONFIG_NAMESPACE_*` -- Namespace reserved / duplicate / env-prefix conflict / env-map conflict (Config Bus) | | `130` | Execution cancelled (Ctrl+C) | @@ -376,8 +377,6 @@ apcore-cli uses a 4-tier configuration precedence: ```yaml extensions: root: ./extensions -logging: - level: DEBUG sandbox: enabled: false cli: diff --git a/cli/rust/src/cli.rs b/cli/rust/src/cli.rs index 20f27580..337bf3c4 100644 --- a/cli/rust/src/cli.rs +++ b/cli/rust/src/cli.rs @@ -882,7 +882,8 @@ pub(crate) fn bypasses_executor_acl(has_script_executable: bool, use_sandbox: bo /// * `APPROVAL_DENIED` / `APPROVAL_TIMEOUT` / `APPROVAL_PENDING` → 46 /// * `CONFIG_NOT_FOUND` / `CONFIG_INVALID` / `ACL_RULE_ERROR` → 47 /// * `SCHEMA_CIRCULAR_REF` → 48 -/// * `ACL_DENIED` → 77 +/// * `POLICY_EVALUATION_ERROR` → 75 +/// * `ACL_DENIED` / `POLICY_DENIED` → 77 /// * everything else (including `MODULE_EXECUTE_ERROR` / `MODULE_TIMEOUT`) → 1 pub(crate) fn map_apcore_error_to_exit_code(error_code: &str) -> i32 { use crate::{ @@ -890,7 +891,7 @@ pub(crate) fn map_apcore_error_to_exit_code(error_code: &str) -> i32 { EXIT_CONFIG_MOUNT_ERROR, EXIT_CONFIG_NAMESPACE_RESERVED, EXIT_CONFIG_NOT_FOUND, EXIT_DEPENDENCY_NOT_FOUND, EXIT_DEPENDENCY_VERSION_MISMATCH, EXIT_ERROR_FORMATTER_DUPLICATE, EXIT_MODULE_EXECUTE_ERROR, EXIT_MODULE_NOT_FOUND, - EXIT_SCHEMA_CIRCULAR_REF, EXIT_SCHEMA_VALIDATION_ERROR, + EXIT_POLICY_EVALUATION_ERROR, EXIT_SCHEMA_CIRCULAR_REF, EXIT_SCHEMA_VALIDATION_ERROR, }; match error_code { "MODULE_NOT_FOUND" | "MODULE_LOAD_ERROR" | "MODULE_DISABLED" => EXIT_MODULE_NOT_FOUND, @@ -908,7 +909,8 @@ pub(crate) fn map_apcore_error_to_exit_code(error_code: &str) -> i32 { // this key together. "ACL_RULE_ERROR" => EXIT_ACL_RULE_ERROR, "SCHEMA_CIRCULAR_REF" => EXIT_SCHEMA_CIRCULAR_REF, - "ACL_DENIED" => EXIT_ACL_DENIED, + "ACL_DENIED" | "POLICY_DENIED" => EXIT_ACL_DENIED, + "POLICY_EVALUATION_ERROR" => EXIT_POLICY_EVALUATION_ERROR, // Config Bus errors (apcore >= 0.15.0) "CONFIG_NAMESPACE_RESERVED" | "CONFIG_NAMESPACE_DUPLICATE" @@ -927,12 +929,28 @@ pub(crate) fn map_apcore_error_to_exit_code(error_code: &str) -> i32 { /// representation via serde JSON serialisation and delegates to /// `map_apcore_error_to_exit_code`. pub(crate) fn map_module_error_to_exit_code(err: &apcore::errors::ModuleError) -> i32 { - // Serialise the ErrorCode enum to its SCREAMING_SNAKE_CASE string. - let code_str = serde_json::to_value(err.code) - .ok() - .and_then(|v| v.as_str().map(|s| s.to_string())) - .unwrap_or_default(); - map_apcore_error_to_exit_code(&code_str) + map_apcore_error_to_exit_code(&module_error_wire_code(err)) +} + +pub(crate) fn module_error_wire_code(error: &apcore::ModuleError) -> String { + match serde_json::to_value(error.code) { + Ok(Value::String(code)) => code, + _ => String::new(), + } +} + +pub(crate) fn policy_error_diagnostic(code: &str) -> Option<(&'static str, bool)> { + match code { + "POLICY_DENIED" => Some(("Policy denied the validated invocation", false)), + "POLICY_EVALUATION_ERROR" => Some(("Policy evaluation failed", true)), + _ => None, + } +} + +fn public_policy_error(data: Option<&Value>) -> Option { + let code = data?.get("code")?.as_str()?; + let (message, retryable) = policy_error_diagnostic(code)?; + Some(serde_json::json!({"code": code, "message": message, "retryable": retryable})) } // --------------------------------------------------------------------------- @@ -1038,7 +1056,8 @@ fn emit_error_json_to( "exit_code": exit_code, }); // Overlay fields from the structured error if available. - if let Some(data) = error_data { + let policy_error = public_policy_error(error_data); + if let Some(data) = policy_error.as_ref().or(error_data) { if let Some(obj) = data.as_object() { for key in &[ "code", @@ -1087,6 +1106,12 @@ fn emit_error_tty_to( error_data: Option<&serde_json::Value>, stream: &ErrorStream, ) { + let policy_error = public_policy_error(error_data); + let error_data = policy_error.as_ref().or(error_data); + let message = policy_error + .as_ref() + .and_then(|data| data["message"].as_str()) + .unwrap_or(message); let mut out = String::new(); // Header with error code. if let Some(code) = error_data @@ -2285,6 +2310,58 @@ async fn run_module_dispatch( mod tests { use super::*; + #[test] + fn policy_diagnostics_mask_protected_message_and_guidance() { + for (code, exit_code, message, retryable) in [ + ( + "POLICY_DENIED", + 77, + "Policy denied the validated invocation", + false, + ), + ( + "POLICY_EVALUATION_ERROR", + 75, + "Policy evaluation failed", + true, + ), + ] { + let data = serde_json::json!({ + "code": code, "message": "private-policy", "details": {"rule": "private-policy"}, + "suggestion": "private-policy", "ai_guidance": "private-policy" + }); + let output = Arc::new(std::sync::Mutex::new(String::new())); + let captured = Arc::clone(&output); + let sink = ErrorStream::Custom(Arc::new(move |line| { + captured.lock().unwrap().push_str(line) + })); + emit_error_json_to( + "test.policy", + "private-policy", + exit_code, + Some(&data), + &sink, + ); + assert_eq!( + serde_json::from_str::(&output.lock().unwrap()).unwrap(), + serde_json::json!({ + "error": true, "code": code, "message": message, "exit_code": exit_code, "retryable": retryable, + }) + ); + output.lock().unwrap().clear(); + emit_error_tty_to( + "test.policy", + "private-policy", + exit_code, + Some(&data), + &sink, + ); + let output = output.lock().unwrap(); + assert!(output.contains(message)); + assert!(!output.contains("private-policy")); + } + } + #[test] fn test_native_validation_error_json_pointers() { const CHILD_MODE: &str = "APCORE_CLI_TEST_NATIVE_ERROR_MODE"; @@ -2798,6 +2875,12 @@ mod tests { assert_eq!(map_apcore_error_to_exit_code("ACL_DENIED"), 77); } + #[test] + fn policy_refusal_is_distinct_from_temporary_evaluation_failure() { + assert_eq!(map_apcore_error_to_exit_code("POLICY_DENIED"), 77); + assert_eq!(map_apcore_error_to_exit_code("POLICY_EVALUATION_ERROR"), 75); + } + #[test] fn test_map_error_module_execute_error_is_1() { assert_eq!(map_apcore_error_to_exit_code("MODULE_EXECUTE_ERROR"), 1); diff --git a/cli/rust/src/lib.rs b/cli/rust/src/lib.rs index 26b72002..56727bd8 100644 --- a/cli/rust/src/lib.rs +++ b/cli/rust/src/lib.rs @@ -70,6 +70,7 @@ pub const EXIT_CONFIG_NOT_FOUND: i32 = 47; // permissions problem. pub const EXIT_ACL_RULE_ERROR: i32 = 47; pub const EXIT_SCHEMA_CIRCULAR_REF: i32 = 48; +pub const EXIT_POLICY_EVALUATION_ERROR: i32 = 75; pub const EXIT_ACL_DENIED: i32 = 77; // Config Bus errors (apcore >= 0.15.0) // All four namespace/env errors share exit code 78 per protocol spec — diff --git a/cli/rust/src/system_cmd.rs b/cli/rust/src/system_cmd.rs index aaed222e..3cc1dfe7 100644 --- a/cli/rust/src/system_cmd.rs +++ b/cli/rust/src/system_cmd.rs @@ -274,7 +274,14 @@ enum SystemDispatchError { impl std::fmt::Display for SystemDispatchError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - SystemDispatchError::ModuleError(e) => write!(f, "{e}"), + SystemDispatchError::ModuleError(e) => { + let code = crate::cli::module_error_wire_code(e); + if let Some((message, _)) = crate::cli::policy_error_diagnostic(&code) { + f.write_str(message) + } else { + write!(f, "{e}") + } + } SystemDispatchError::NoAsyncRuntime => write!(f, "no async runtime available"), } } diff --git a/cli/typescript/README.md b/cli/typescript/README.md index c02af91a..90ef686e 100644 --- a/cli/typescript/README.md +++ b/cli/typescript/README.md @@ -371,7 +371,8 @@ The exit codes below are also exported as the `EXIT_CODES` const-object from `ap | `46` | `APPROVAL_DENIED` / `APPROVAL_TIMEOUT` | Approval denied or timed out | | `47` | `CONFIG_NOT_FOUND` / `CONFIG_INVALID` | Configuration error | | `48` | `SCHEMA_CIRCULAR_REF` | Schema circular reference | -| `77` | `ACL_DENIED` | ACL denied | +| `75` | `POLICY_EVALUATION_ERROR` | Policy evaluation failed (retryable) | +| `77` | `ACL_DENIED` | ACL or policy denied | | `130` | *(no key — set by signal handler)* | Execution cancelled (Ctrl+C) | ## Configuration @@ -404,8 +405,6 @@ apcore-cli uses a 4-tier configuration precedence: ```yaml extensions: root: ./extensions -logging: - level: DEBUG sandbox: enabled: false cli: diff --git a/cli/typescript/src/error-output.ts b/cli/typescript/src/error-output.ts index 0f5801f5..1d3a83f1 100644 --- a/cli/typescript/src/error-output.ts +++ b/cli/typescript/src/error-output.ts @@ -60,21 +60,38 @@ export async function reportModuleError( (options.exit ?? exitWith)(failure.exitCode); } +export function policyErrorDiagnostic(error: unknown): { message: string; retryable: boolean } | undefined { + const code = (error as { code?: unknown } | null)?.code; + switch (code) { + case "POLICY_DENIED": + return { message: "Policy denied the validated invocation", retryable: false }; + case "POLICY_EVALUATION_ERROR": + return { message: "Policy evaluation failed", retryable: true }; + default: + return undefined; + } +} + /** Emit the single-line JSON error document (F3). */ export function emitErrorJson(e: unknown, exitCode: number, out: ErrorWriter = process.stderr): void { const err = e instanceof Error ? e : new Error(String(e)); const errRecord = err as unknown as Record; const code = errRecord.code ?? "UNKNOWN"; + const policy = policyErrorDiagnostic(err); const payload: Record = { error: true, code, - message: err.message, + message: policy?.message ?? err.message, exit_code: exitCode, }; - for (const field of ["details", "suggestion", "ai_guidance", "retryable", "user_fixable"]) { - const val = errRecord[field]; - if (val !== undefined && val !== null) { - payload[field] = val; + if (policy) { + payload.retryable = policy.retryable; + } else { + for (const field of ["details", "suggestion", "ai_guidance", "retryable", "user_fixable"]) { + const val = errRecord[field]; + if (val !== undefined && val !== null) { + payload[field] = val; + } } } out.write(JSON.stringify(payload) + "\n"); @@ -85,10 +102,12 @@ export function emitErrorTty(e: unknown, exitCode: number, out: ErrorWriter = pr const err = e instanceof Error ? e : new Error(String(e)); const errRecord = err as unknown as Record; const code = errRecord.code; - const header = code ? `Error [${code}]: ${err.message}` : `Error: ${err.message}`; + const policy = policyErrorDiagnostic(err); + const message = policy?.message ?? err.message; + const header = code ? `Error [${code}]: ${message}` : `Error: ${message}`; out.write(header + "\n"); - const details = errRecord.details; + const details = policy ? undefined : errRecord.details; if (details && typeof details === "object" && !Array.isArray(details)) { out.write("\n Details:\n"); for (const [k, v] of Object.entries(details as Record)) { @@ -102,12 +121,12 @@ export function emitErrorTty(e: unknown, exitCode: number, out: ErrorWriter = pr } } - const suggestion = errRecord.suggestion; + const suggestion = policy ? undefined : errRecord.suggestion; if (suggestion) { out.write(`\n Suggestion: ${suggestion}\n`); } - const retryable = errRecord.retryable; + const retryable = policy?.retryable ?? errRecord.retryable; if (retryable !== undefined && retryable !== null) { const label = retryable ? "Yes" : "No (same input will fail again)"; out.write(` Retryable: ${label}\n`); diff --git a/cli/typescript/src/errors.ts b/cli/typescript/src/errors.ts index 942233db..4c08f3df 100644 --- a/cli/typescript/src/errors.ts +++ b/cli/typescript/src/errors.ts @@ -126,6 +126,7 @@ export const EXIT_CODES = { */ ACL_RULE_ERROR: 47, SCHEMA_CIRCULAR_REF: 48, + POLICY_EVALUATION_ERROR: 75, ACL_DENIED: 77, // Config Bus errors (apcore >= 0.15.0) CONFIG_NAMESPACE_RESERVED: 78, @@ -199,6 +200,8 @@ export function exitCodeForError(error: unknown): ExitCode { MODULE_EXECUTE_ERROR: EXIT_CODES.MODULE_EXECUTE_ERROR, MODULE_TIMEOUT: EXIT_CODES.MODULE_TIMEOUT, ACL_DENIED: EXIT_CODES.ACL_DENIED, + POLICY_DENIED: EXIT_CODES.ACL_DENIED, + POLICY_EVALUATION_ERROR: EXIT_CODES.POLICY_EVALUATION_ERROR, // FE-14 §6.1 — a malformed ACL file is a config fault (47), never a // denial (77). Cross-SDK map parity: Python / Rust carry the same row. ACL_RULE_ERROR: EXIT_CODES.ACL_RULE_ERROR, diff --git a/cli/typescript/src/system-cmd.ts b/cli/typescript/src/system-cmd.ts index 5a384af1..a829c10a 100644 --- a/cli/typescript/src/system-cmd.ts +++ b/cli/typescript/src/system-cmd.ts @@ -10,6 +10,7 @@ import { Command } from "commander"; import { Config } from "apcore-js/config"; import { checkApproval } from "./approval.js"; import type { Executor, ModuleDescriptor } from "./cli.js"; +import { policyErrorDiagnostic } from "./error-output.js"; import { exitCodeForError } from "./errors.js"; import { exitWith } from "./exit.js"; import { formatExecResult, resolveFormat } from "./output.js"; @@ -55,7 +56,8 @@ function emitResult( // so scripted callers can distinguish ACL_DENIED (77) from MODULE_NOT_FOUND (44) // from generic MODULE_EXECUTE_ERROR (1). function emitErrorAndExit(e: unknown): never { - process.stderr.write(`Error: ${e instanceof Error ? e.message : e}\n`); + const message = policyErrorDiagnostic(e)?.message ?? (e instanceof Error ? e.message : e); + process.stderr.write(`Error: ${message}\n`); exitWith(exitCodeForError(e)); } diff --git a/cli/typescript/tests/errors.test.ts b/cli/typescript/tests/errors.test.ts index b637fe6d..cd394fbe 100644 --- a/cli/typescript/tests/errors.test.ts +++ b/cli/typescript/tests/errors.test.ts @@ -3,6 +3,7 @@ */ import { describe, it, expect } from "vitest"; +import { emitErrorJson, emitErrorTty } from "../src/error-output.js"; import { ApprovalTimeoutError, ApprovalDeniedError, @@ -83,6 +84,13 @@ describe("exitCodeForError", () => { expect(exitCodeForError(new AuthenticationError())).toBe(EXIT_CODES.ACL_DENIED); }); + it("distinguishes policy refusal from temporary evaluation failure", () => { + const denied = Object.assign(new Error("denied"), { code: "POLICY_DENIED" }); + const failed = Object.assign(new Error("unavailable"), { code: "POLICY_EVALUATION_ERROR" }); + expect(exitCodeForError(denied)).toBe(77); + expect(exitCodeForError(failed)).toBe(75); + }); + it("maps ConfigDecryptionError to exit code 47", () => { expect(exitCodeForError(new ConfigDecryptionError())).toBe(EXIT_CODES.CONFIG_INVALID); }); @@ -168,3 +176,21 @@ describe("exitCodeForError", () => { expect(exitCodeForError(err)).toBe(EXIT_CODES.ERROR_FORMATTER_DUPLICATE); }); }); + + +it.each([ + ["POLICY_DENIED", 77, "Policy denied the validated invocation", false], + ["POLICY_EVALUATION_ERROR", 75, "Policy evaluation failed", true], +])("masks protected diagnostics for %s", (code, exitCode, message, retryable) => { + const error = Object.assign(new Error("private-policy"), { + code, details: { rule: "private-policy" }, suggestion: "private-policy", ai_guidance: "private-policy", + }); + let output = ""; + const sink = { write: (text: string) => { output += text; } }; + emitErrorJson(error, exitCode, sink); + expect(JSON.parse(output)).toEqual({ error: true, code, message, exit_code: exitCode, retryable }); + output = ""; + emitErrorTty(error, exitCode, sink); + expect(output).toContain(message); + expect(output).not.toContain("private-policy"); +}); diff --git a/mcp/README.md b/mcp/README.md index c1292551..da75fdfe 100644 --- a/mcp/README.md +++ b/mcp/README.md @@ -96,28 +96,19 @@ === "🦀 Rust" ```rust + use apcore::{APCore, ModulePack}; use apcore_mcp::APCoreMCP; - use apcore::{Config, Executor}; - use std::sync::Arc; - // Rust cannot discover modules from a directory — see the note below. - // Register your modules, then hand the builder an Executor. - let registry = build_my_registry(); - let executor = Arc::new(Executor::new(registry, Config::default())); - - let mcp = APCoreMCP::builder() - .backend(executor) - .build()?; - mcp.serve()?; + fn serve_pack(core: &APCore, pack: &ModulePack) -> Result<(), Box> { + pack.register(core)?; + APCoreMCP::builder().backend(core.executor_arc()).build()?.serve()?; + Ok(()) + } ``` - !!! warning "Rust does not support directory auto-discovery yet" - `.backend("./extensions")` and the CLI's `--extensions-dir` compile and run, but they build - an **empty registry** with a warning — apcore's public Rust API has no runtime directory - discovery. The server starts and serves zero user modules (only the `__apcore_*` meta-tools). - Use `BackendSource::Registry` — a `Registry`/`Executor` you construct in code — which is - fully supported. Tracked in the CHANGELOG under *Known limitations (Rust)*; the Python and - TypeScript paths above are unaffected. + The [`ModulePack`](docs/getting-started.md#3-programmatic-usage) API requires + the Core `macros` feature. The Rust CLI + serves OpenAPI backends through `--from-openapi` and rejects `--extensions-dir`. === "💻 CLI" @@ -129,8 +120,8 @@ apcore-mcp --extensions-dir ./extensions --transport streamable-http --port 8000 --explorer ``` - *The Python and TypeScript CLIs discover modules from the directory. The **Rust** CLI does not — - `--extensions-dir` builds an empty registry there; see the Rust tab above.* + The commands above use the Python or TypeScript CLI. With the Rust CLI, use + `apcore-mcp --from-openapi ./openapi.yaml`. ### 2. Export as OpenAI Tools @@ -164,14 +155,9 @@ let tools = mcp.to_openai_tools(false, true)?; ``` -!!! note "`strict` does not default the same way in all three" - Written exactly as above, the three tabs produce **different** OpenAI schemas from the same - registry: Python's `to_openai_tools()` defaults `strict=False` and emits permissive schemas, - while TypeScript's `toOpenaiTools()` defaults to `true` and the Rust call passes `true` - positionally — both emit strict ones (`additionalProperties: false`, every property forced into - `required`, nullable types wrapped, `"strict": true` on the function). OpenAI's function-calling - treats the two shapes differently. **Pass `strict` explicitly** in anything portable: - `mcp.to_openai_tools(strict=True)` / `mcp.toOpenaiTools({ strict: true })`. +Python and TypeScript default to strict OpenAI schemas. Rust's positional API +requires an explicit `strict` argument. Use `strict=False` in Python or +`{ strict: false }` in TypeScript to request permissive schemas. --- diff --git a/mcp/docs/configuration.md b/mcp/docs/configuration.md index 675a542b..fb46c953 100644 --- a/mcp/docs/configuration.md +++ b/mcp/docs/configuration.md @@ -17,11 +17,11 @@ The CLI allows you to launch an MCP server by pointing to an extensions director >= 0.32.0 and apcore-toolkit >= 0.14.0. The scanner emits module IDs in apcore's alphabet since toolkit 0.13.0 (see [OpenAPI Backend § `module_id` → tool name](features/openapi-backend.md#module_id-tool-name)). -**Backend-source rule.** **At least one** source is required. The two may be combined — an apcore project and a remote API served from one bridge is a supported deployment — and when more than one is given, `--openapi-prefix` becomes **required** so the two ID spaces cannot collide. The resulting registry is the **union**, assembled in a fixed order: extensions directory first, then OpenAPI operations. Order matters only for diagnostics; a module ID appearing in both sources is a startup failure, not a last-writer-wins merge (see [OpenAPI Backend § ID collisions](features/openapi-backend.md#id-collisions-are-a-startup-failure)). A `Registry` or `Executor` passed programmatically **replaces** both — it is not merged with them, because the caller who built it already decided what is in it; passing one together with `--extensions-dir` or `--from-openapi` is a configuration error rather than a silent override. +In Python and TypeScript, use an extensions directory, an OpenAPI document, or both. When combining them, pass `--openapi-prefix` to separate the module IDs. A duplicate ID stops startup. See [OpenAPI backend collisions](features/openapi-backend.md#id-collisions-are-a-startup-failure). The Rust CLI requires `--from-openapi` or `mcp.openapi.spec` in the Config Bus. An embedded host can supply its own `Registry` or `Executor` as the sole backend. Combining that explicit backend with either CLI source is a configuration error. | Argument | Default | Description | |---|---|---| -| `--extensions-dir` | *(required unless `--from-openapi` is given)* | Path to apcore extensions directory. **Rust:** accepted, but builds an empty registry — see [Getting Started §2](getting-started.md) | +| `--extensions-dir` | — | Path to apcore extensions directory for Python and TypeScript. The standalone Rust CLI rejects this flag. | | `--from-openapi` | — | Spec URL or path — serve an OpenAPI 3.0/3.1 API as MCP tools instead of (or alongside) an extensions directory. See [OpenAPI Backend](features/openapi-backend.md) | | `--openapi-base-url` | from document | Base URL for proxied requests; defaults to the document's `servers[0].url` | | `--openapi-prefix` | — | Prepended to every derived module ID. **Required** when `--from-openapi` is combined with another backend source | @@ -325,10 +325,8 @@ The `async_serve` function returns an embeddable ASGI application (Starlette) fo Converts apcore modules into OpenAI-compatible tool definitions. -!!! warning "`strict` has a different default in each language" - Python defaults to `False`, TypeScript to `true`, and Rust takes it positionally with no default. - Omitting it therefore gives you permissive schemas from Python and strict ones from the other - two, for the same registry. Pass it explicitly. +Python and TypeScript default to strict conversion. Rust's positional API takes +an explicit `strict` argument. Set `strict` to false for permissive conversion. === "Python" @@ -338,7 +336,7 @@ Converts apcore modules into OpenAI-compatible tool definitions. tools = to_openai_tools( registry_or_executor, embed_annotations=False, # Append annotation hints to descriptions - strict=False, # Enable OpenAI Structured Outputs strict mode + strict=True, # Default for OpenAI Structured Outputs tags=None, # Filter modules by tags (list of strings) prefix=None, # Filter modules by ID prefix ) diff --git a/mcp/docs/features/approval-handler.md b/mcp/docs/features/approval-handler.md index a36db6d1..b8676e00 100644 --- a/mcp/docs/features/approval-handler.md +++ b/mcp/docs/features/approval-handler.md @@ -98,7 +98,11 @@ The system supports global approval modes via the `--approval` CLI flag: - request: ApprovalRequest, required, validates[has `context`, `module_id`, `description`, `arguments` fields], reject_with=ApprovalResult(status="rejected") - request.context.data[MCP_ELICIT_KEY]: async callable, required per-call (Python / TypeScript) — extracted from context at call time (not constructor), reject_with=ApprovalResult(status="rejected", reason="No elicitation callback available") -> **Rust contract variation**: `ElicitationApprovalHandler::new(elicit)` accepts an `Option>` at construction. Because Rust's `Context` (with `serde_json::Value`) cannot store async closures, the handler cannot extract a callback from `request.context.data` per-call (which is always the case for Rust's `serde_json::Value`-typed context). Instead, Rust uses the constructor-injected callback for every `request_approval` call. The rejection semantics ("No context available for elicitation", "No elicitation callback available") are preserved: if construction omitted the callback, the handler returns `ApprovalResult(status="rejected", reason="No elicitation callback available")`. +Rust calls `request.context.elicit` first. If the context has no native handler, +the adapter uses the session callback identified by `MCP_ELICIT_CALL_ID_KEY`, +then the optional callback passed to `ElicitationApprovalHandler::new`. Native +errors do not trigger another prompt. Cancellation and deadlines propagate to +Core. A request with no context or callback is rejected. ### Errors - Returns `ApprovalResult(status="rejected", reason="No context available for elicitation")` — when request.context is None or has no `data` @@ -126,7 +130,7 @@ The elicit-callback source differs between Python/TypeScript and Rust: |--------------|------------------------------------------------------------------------------| | Python | `request.context.data[MCP_ELICIT_KEY]` (per-call lookup in execution context)| | TypeScript | `request.context.data[MCP_ELICIT_KEY]` (per-call lookup in execution context)| -| Rust | Constructor-injected `Option>` (set on handler ctor) | +| Rust | `Context::elicit`, then a request-local session callback or `Option` from the constructor | The wire-level rejection semantics ("No context available for elicitation", "No elicitation callback available", "Elicitation request failed", "Elicitation returned no response") are preserved across all three SDKs. The structural difference exists because Rust's `Context` is parameterized over `serde_json::Value`, which cannot hold async closures. diff --git a/mcp/docs/features/mcp-server-factory.md b/mcp/docs/features/mcp-server-factory.md index 764f94ce..84bf1881 100644 --- a/mcp/docs/features/mcp-server-factory.md +++ b/mcp/docs/features/mcp-server-factory.md @@ -177,10 +177,10 @@ 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 Python adapter also supports a direct `ArtifactRef` field that uses the -Core artifact assertions and `x-mcp-artifact: true`. It checks the final field -against the store's actual media type and byte count. Python hosts can use the -same `MCPArtifactStore` with Core's `read_artifact` helper. +All three adapters also support a direct `ArtifactRef` object declared with +the Core artifact assertions and `x-mcp-artifact: true`. The final reference +must match the authorized store entry's media type and byte count. Python and +Rust hosts can also pass their `MCPArtifactStore` to Core's `read_artifact` helper. The adapter appends a native `resource_link` for a successful, validated structured tool result on supported MCP versions. The same result still diff --git a/mcp/docs/features/openai-converter.md b/mcp/docs/features/openai-converter.md index 0b211239..672c3fff 100644 --- a/mcp/docs/features/openai-converter.md +++ b/mcp/docs/features/openai-converter.md @@ -117,7 +117,7 @@ The converter must return only standard Python types (dict, list, str, etc.) and ### Inputs - registry: Any, required (duck-typed) — must expose `list(tags?, prefix?)` and `get_definition(module_id)` methods; NOT a raw JSON Value - embed_annotations: bool, optional, default=False — when True, appends annotation suffix to descriptions -- strict: bool, optional, default=False (Python; TypeScript default is True per OC-1) +- strict: bool, optional, default=True - tags: list[str] | None, optional — filter passed to registry.list() - prefix: str | None, optional — filter passed to registry.list() @@ -168,7 +168,7 @@ The converter must return only standard Python types (dict, list, str, etc.) and ### Inputs - registry: Any, required (duck-typed) — same contract as OpenAIConverter.convert_registry -- strict: bool, optional, default=False +- strict: bool, optional, default=True - embed_annotations: bool, optional, default=False - tags: list[str] | None, optional - prefix: str | None, optional diff --git a/mcp/docs/features/openapi-backend.md b/mcp/docs/features/openapi-backend.md index b98d6976..b0cf8da8 100644 --- a/mcp/docs/features/openapi-backend.md +++ b/mcp/docs/features/openapi-backend.md @@ -88,7 +88,7 @@ load_spec(url|path) → OpenAPIScanner.scan() → HTTPProxyRegistryWriter.write( | Source | Python | TypeScript | Rust | |---|---|---|---| -| Extensions directory | ✅ | ✅ | ⚠️ builds an empty registry ([Getting Started §2](../getting-started.md)) | +| Extensions directory | ✅ | ✅ | Unsupported ([Getting Started §2](../getting-started.md)) | | `Registry` / `Executor` built in code | ✅ | ✅ | ✅ | | **OpenAPI document** | ✅ | ✅ | ✅ | @@ -426,7 +426,7 @@ milliseconds was [apcore-mcp-typescript#10](https://github.com/aiperceivable/apc | Argument | Default | Description | |---|---|---| -| `--from-openapi` | — | Spec URL or path. Mutually exclusive with `--extensions-dir` unless `--openapi-prefix` is given | +| `--from-openapi` | — | Spec URL or path. Python and TypeScript require `--openapi-prefix` when combining with `--extensions-dir`. | | `--openapi-base-url` | from document | Base URL for proxied requests | | `--openapi-prefix` | — | `base_path_prefix` for every derived module ID | | `--openapi-include` / `--openapi-exclude` | — | Scanner filters | diff --git a/mcp/docs/getting-started.md b/mcp/docs/getting-started.md index 8280c00f..e5ccac1b 100644 --- a/mcp/docs/getting-started.md +++ b/mcp/docs/getting-started.md @@ -62,23 +62,15 @@ If you have an `extensions/` directory containing your apcore modules, you can l === "Rust" - !!! warning "`--extensions-dir` does not discover modules in the Rust CLI" - The Rust binary accepts the flag and starts, but builds an **empty registry** with a warning - — apcore's public Rust API has no runtime directory discovery. You get a working server with - zero user tools (only the `__apcore_*` meta-tools). There is no zero-code path in Rust yet: - build a `Registry` → `Executor` in code and use the programmatic API in §3 below. Tracked in - the CHANGELOG under *Known limitations (Rust)*. + The standalone Rust binary serves OpenAPI backends and rejects `--extensions-dir`. + For native Rust modules, use the compiled host in [Programmatic Usage](#3-programmatic-usage). ```bash - # stdio (default) — starts, but serves no user modules today - apcore-mcp --extensions-dir ./extensions + # stdio (default) + apcore-mcp --from-openapi ./openapi.yaml # HTTP with Tool Explorer UI - apcore-mcp --extensions-dir ./extensions - --transport streamable-http - --port 8000 - --explorer - --allow-execute + apcore-mcp --from-openapi ./openapi.yaml --transport streamable-http --port 8000 --explorer --allow-execute ``` Once running in HTTP mode with `--explorer`, visit `http://127.0.0.1:8000/explorer/` to browse and test your tools. @@ -112,6 +104,19 @@ Integrate **apcore-mcp** directly into your application. The `APCoreMCP` class i mcp = APCoreMCP("./extensions", output_formatter=to_markdown) ``` + With the Core `macros` feature, register a compiled pack in your `APCore` + instance and pass its executor to MCP: + + ```rust + // NOTES is a ModulePack built from compiled #[apcore::module] declarations. + NOTES.register(&core)?; + let mcp = APCoreMCP::builder().backend(core.executor_arc()).build()?; + mcp.serve()?; + ``` + + See the [Core Golden Path](https://github.com/aiperceivable/apcore/blob/main/examples/rust/golden-path/verify.rs) + for the pack declaration and execution with approval and policy enabled. + You can also pass an existing Registry or Executor: ```python @@ -190,7 +195,6 @@ Integrate **apcore-mcp** directly into your application. The `APCoreMCP` class i use apcore::{config::Config, executor::Executor, registry::registry::Registry}; use apcore_mcp::APCoreMCP; - // BackendSource::Executor is the functional backend (as of v0.15.0). // Construct Registry → Executor first, then hand the Arc to APCoreMCP. let registry = Registry::new(); // ... register modules ... @@ -264,16 +268,12 @@ Add this to `~/Library/Application Support/Claude/claude_desktop_config.json` (m "mcpServers": { "apcore": { "command": "apcore-mcp", - "args": ["--extensions-dir", "/absolute/path/to/your/extensions"] + "args": ["--from-openapi", "/absolute/path/to/openapi.yaml"] } } } ``` - *This config launches the Rust binary successfully but exposes no user modules — see the - `--extensions-dir` warning in §2. Point your client at the Python or TypeScript binary, or wrap - the Rust programmatic API in your own binary.* - ### Cursor / Claude Code / Windsurf Add a `.mcp.json` or equivalent in your project root: diff --git a/mcp/docs/prd-apcore-mcp.md b/mcp/docs/prd-apcore-mcp.md index 73a67266..8acbadaf 100644 --- a/mcp/docs/prd-apcore-mcp.md +++ b/mcp/docs/prd-apcore-mcp.md @@ -513,7 +513,7 @@ tools = to_openai_tools(registry, strict=True) **Acceptance Criteria:** 1. `to_openai_tools(registry, strict=True)` adds `"strict": true` to each function definition. -2. `to_openai_tools(registry, strict=False)` (default) does not add the strict field. +2. `to_openai_tools(registry, strict=False)` does not add the strict field. 3. When strict mode is enabled, schemas are validated to be strict-mode-compatible (e.g., all properties required, no `additionalProperties`). Incompatible schemas produce a warning. **Priority:** P1 diff --git a/mcp/docs/srs-apcore-mcp.md b/mcp/docs/srs-apcore-mcp.md index 0b128371..d680950d 100644 --- a/mcp/docs/srs-apcore-mcp.md +++ b/mcp/docs/srs-apcore-mcp.md @@ -1617,7 +1617,7 @@ preserved unchanged, including `keyword`. **Expected Output:** Each tool dict has `"function": {"strict": true, ...}` and the `"parameters"` schema follows strict mode rules. **Boundary Conditions:** -- `strict=False` (default): No `"strict"` key in function dict. Schema not transformed. +- `strict=False`: No `"strict"` key in function dict. Schema not transformed. - Schema already has `"additionalProperties": false`: No change needed for that property. - Schema with no optional properties: All properties already required; no nullable conversion needed. - Schema with deeply nested objects: Strict mode rules applied recursively. @@ -4515,7 +4515,7 @@ The next SDK release follows the complete [structured tool result contract](feat |-----------|------|----------|---------|-------------|-------------| | `registry_or_executor` | `Registry \| Executor` | Yes | N/A | Must be instance of Registry or Executor | Module source | | `embed_annotations` | `bool` | No | `False` | N/A | Append annotation metadata to descriptions | -| `strict` | `bool` | No | `False` (Python) / `True` (TypeScript, Rust) | N/A | Enable OpenAI strict mode. **The default is not uniform**: Python's `to_openai_tools()` defaults to `False`, TypeScript's `toOpenaiTools()` to `True`, and Rust's `to_openai_tools(embed_annotations, strict)` takes it positionally with no default (documented call sites pass `true`). The same registry therefore yields permissive schemas from Python and strict ones from the other two. Pass the value explicitly in portable code. | +| `strict` | `bool` | No | `True` (Python and TypeScript) | N/A | Enable OpenAI strict mode. Rust's positional API takes an explicit value. Pass `false` to opt out. | | `tags` | `list[str] \| None` | No | `None` | Each tag non-empty | Tag filter | | `prefix` | `str \| None` | No | `None` | Non-empty if provided | Prefix filter | @@ -4650,7 +4650,7 @@ def to_openai_tools( registry_or_executor: Registry | Executor, *, embed_annotations: bool = False, - strict: bool = False, + strict: bool = True, tags: list[str] | None = None, prefix: str | None = None, ) -> list[dict[str, Any]]: ... diff --git a/mcp/docs/tech-design-apcore-mcp.md b/mcp/docs/tech-design-apcore-mcp.md index 7f627c75..05c05756 100644 --- a/mcp/docs/tech-design-apcore-mcp.md +++ b/mcp/docs/tech-design-apcore-mcp.md @@ -1335,7 +1335,7 @@ class OpenAIConverter: self, registry: Registry, embed_annotations: bool = False, - strict: bool = False, + strict: bool = True, tags: list[str] | None = None, prefix: str | None = None, ) -> list[dict[str, Any]]: @@ -1349,7 +1349,7 @@ class OpenAIConverter: strict: If True, add "strict": true to each function definition and convert schemas to strict mode (additionalProperties=false, all properties required, optional fields become nullable). - Type: bool. Default: False. + Type: bool. Default: True. tags: Optional tag filter. Type: list[str] | None. Default: None. prefix: Optional module_id prefix filter. @@ -1373,7 +1373,7 @@ class OpenAIConverter: self, descriptor: ModuleDescriptor, embed_annotations: bool = False, - strict: bool = False, + strict: bool = True, ) -> dict[str, Any]: """Convert a single ModuleDescriptor to an OpenAI tool definition. @@ -2540,7 +2540,7 @@ def to_openai_tools( registry_or_executor: Registry | Executor, *, embed_annotations: bool = False, - strict: bool = False, + strict: bool = True, tags: list[str] | None = None, prefix: str | None = None, ) -> list[dict[str, Any]]: diff --git a/mcp/python/pyproject.toml b/mcp/python/pyproject.toml index 13599ad2..2adabbe4 100644 --- a/mcp/python/pyproject.toml +++ b/mcp/python/pyproject.toml @@ -70,7 +70,7 @@ apcore-mcp = "apcore_mcp.__main__:main" [project.urls] Homepage = "https://aiperceivable.com" Repository = "https://github.com/aiperceivable/apcore-surfaces/tree/main/mcp/python" -Documentation = "https://github.com/aiperceivable/apcore-mcp-python#readme" +Documentation = "https://aiperceivable.github.io/apcore-surfaces/mcp/" Issues = "https://github.com/aiperceivable/apcore-surfaces/issues" [tool.hatch.build.targets.wheel] diff --git a/mcp/python/src/apcore_mcp/apcore_mcp.py b/mcp/python/src/apcore_mcp/apcore_mcp.py index c01e73d8..471de9fe 100644 --- a/mcp/python/src/apcore_mcp/apcore_mcp.py +++ b/mcp/python/src/apcore_mcp/apcore_mcp.py @@ -1161,13 +1161,13 @@ def to_openai_tools( self, *, embed_annotations: bool = False, - strict: bool = False, + strict: bool = True, ) -> list[dict]: """Export modules as OpenAI-compatible tool definitions. Args: embed_annotations: Embed annotation metadata in tool descriptions. - strict: Add strict: true for OpenAI Structured Outputs. + strict: Enable OpenAI Structured Outputs. Pass False for permissive schemas. Returns: List of OpenAI tool definition dicts, directly usable with diff --git a/mcp/python/src/apcore_mcp/server/factory.py b/mcp/python/src/apcore_mcp/server/factory.py index c98f4d8c..3cfb1567 100644 --- a/mcp/python/src/apcore_mcp/server/factory.py +++ b/mcp/python/src/apcore_mcp/server/factory.py @@ -14,14 +14,15 @@ import anyio import jsonschema # type: ignore[import-untyped] # MCP supplies jsonschema without its optional typing stubs. -from apcore import CancelToken, Identity, ModuleError +from apcore import CancelToken, Identity, ModuleError, SchemaParseError from apcore import Registry as CoreRegistry +from apcore.schema.hardening import validate_schema_dict from mcp import types as mcp_types from mcp.server.lowlevel import NotificationOptions, Server from mcp.server.lowlevel.helper_types import ReadResourceContents from mcp.server.models import InitializationOptions from mcp.shared.version import SUPPORTED_PROTOCOL_VERSIONS -from pydantic import AnyUrl +from pydantic import AnyUrl, ValidationError from referencing import Registry, Resource from referencing.jsonschema import DRAFT7, DRAFT201909, DRAFT202012 @@ -40,10 +41,9 @@ from apcore_mcp.server.transport import _protocol_source_var, _scoped_sse_request, transport_session_var try: - from apcore._artifact_projection import is_direct_artifact_reference, parse_artifact_reference + from apcore.artifacts import ArtifactRef except ImportError: - is_direct_artifact_reference = None # type: ignore[assignment] - parse_artifact_reference = None # type: ignore[assignment] + ArtifactRef = None # type: ignore[assignment] logger = logging.getLogger(__name__) @@ -53,6 +53,23 @@ _AI_INTENT_KEYS = ("x-when-to-use", "x-when-not-to-use", "x-common-mistakes", "x-workflow-hints") _ARTIFACT_REFERENCE_ASSERTIONS = frozenset({"x-artifact-ref", "x-media-types", "x-max-bytes"}) +_ARTIFACT_REFERENCE_FIELDS = frozenset({"type", "title", "description"}) +_ARTIFACT_ROOT_APPLICATORS = frozenset( + { + "$ref", + "$dynamicRef", + "$recursiveRef", + "allOf", + "anyOf", + "oneOf", + "if", + "then", + "else", + "dependentSchemas", + "dependencies", + "patternProperties", + } +) # aiperceivable/apcore-mcp#15: the three read-only `system.*` namespaces. # `system.control.*` is deliberately excluded -- it performs writes and stays @@ -1024,6 +1041,11 @@ def _attach_artifact_links( properties = schema.get("properties") if not isinstance(properties, dict): return + direct_reference_root = ( + schema.get("type") == "object" + and not schema.get("x-sensitive") + and _ARTIFACT_ROOT_APPLICATORS.isdisjoint(schema) + ) emitted: set[str] = set() for name, definition in properties.items(): if not isinstance(definition, dict) or definition.get("x-mcp-artifact") is not True: @@ -1034,14 +1056,23 @@ def _attach_artifact_links( reference = None if not _ARTIFACT_REFERENCE_ASSERTIONS.isdisjoint(definition): if ( - is_direct_artifact_reference is None - or parse_artifact_reference is None + ArtifactRef is None + or not direct_reference_root + or definition.get("x-sensitive") or not isinstance(value, dict) - or not is_direct_artifact_reference(schema, definition) + or definition.get("type") not in (None, "object") + or any( + key not in _ARTIFACT_REFERENCE_FIELDS + and (not isinstance(key, str) or not key.startswith("x-")) + for key in definition + ) ): continue - reference = parse_artifact_reference(value, definition) - if reference is None: + try: + if not validate_schema_dict(value, definition).valid: + continue + reference = ArtifactRef.model_validate(value) + except (SchemaParseError, ValidationError): continue elif definition.get("type") != "string": continue diff --git a/mcp/python/tests/server/test_artifact_wire.py b/mcp/python/tests/server/test_artifact_wire.py index 76608546..6c95a006 100644 --- a/mcp/python/tests/server/test_artifact_wire.py +++ b/mcp/python/tests/server/test_artifact_wire.py @@ -14,12 +14,16 @@ from tests.server.test_scoped_approval_wire import _HttpSession -@pytest.mark.parametrize("downgrade_artifact", [False, True]) -async def test_tool_link_and_binary_read_require_the_registered_authority(downgrade_artifact: bool): +@pytest.mark.parametrize("artifact_mode", ["legacy", "reference", "downgrade"]) +async def test_tool_link_and_binary_read_require_the_registered_authority(artifact_mode: str): 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) + payload = b"image bytes" + artifact_id = store.put(payload, name="preview.png", mime_type="image/png", owner=owner) + downgrade_artifact = artifact_mode == "downgrade" + reference_size = 1 if downgrade_artifact else len(payload) + reference = {"id": artifact_id, "media_type": "image/png", "size_bytes": reference_size} class Authenticator: def authenticate(self, headers): @@ -33,15 +37,15 @@ class Preview: "properties": {"artifact": {"type": "string", "x-mcp-artifact": True}}, "required": ["artifact"], } - if downgrade_artifact: + if artifact_mode != "legacy": output_schema["properties"]["artifact"] = { - "x-artifact-ref": True, "x-max-bytes": 1, "x-mcp-artifact": True, + "x-artifact-ref": True, + "x-max-bytes": reference_size, + "x-mcp-artifact": True, } async def execute(self, _inputs, _context): - if downgrade_artifact: - return {"artifact": {"id": artifact_id, "media_type": "image/png", "size_bytes": 1}} - return {"artifact": artifact_id} + return {"artifact": artifact_id if artifact_mode == "legacy" else reference} class DowngradeArtifact(Middleware): def after(self, _module_id, _inputs, output, _context): @@ -67,8 +71,9 @@ def after(self, _module_id, _inputs, output, _context): 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} + expected = {"artifact": reference if artifact_mode == "reference" else artifact_id} + assert result["structuredContent"] == expected + assert json.loads(result["content"][0]["text"]) == expected if downgrade_artifact: assert [item["type"] for item in result["content"]] == ["text"] return @@ -81,7 +86,7 @@ def after(self, _module_id, _inputs, output, _context): 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" + assert base64.b64decode(binary["blob"]) == payload guest_result = await guest_session.request("tools/call", call) assert [item["type"] for item in guest_result["content"]] == ["text"] diff --git a/mcp/python/tests/test_apcore_mcp.py b/mcp/python/tests/test_apcore_mcp.py index edc39b95..893d5937 100644 --- a/mcp/python/tests/test_apcore_mcp.py +++ b/mcp/python/tests/test_apcore_mcp.py @@ -374,7 +374,7 @@ def test_to_openai_tools(self) -> None: mock_converter.convert_registry.assert_called_once_with( registry, embed_annotations=False, - strict=False, + strict=True, tags=None, prefix=None, ) @@ -387,11 +387,11 @@ def test_to_openai_tools_with_options(self) -> None: mock_converter = mock_converter_cls.return_value mock_converter.convert_registry.return_value = [] - mcp.to_openai_tools(embed_annotations=True, strict=True) + mcp.to_openai_tools(embed_annotations=True, strict=False) mock_converter.convert_registry.assert_called_once_with( registry, embed_annotations=True, - strict=True, + strict=False, tags=["public"], prefix="api", ) diff --git a/mcp/rust/Cargo.toml b/mcp/rust/Cargo.toml index 175e3582..3baf5049 100644 --- a/mcp/rust/Cargo.toml +++ b/mcp/rust/Cargo.toml @@ -9,7 +9,7 @@ readme = "README.md" authors = ["aiperceivable "] homepage = "https://aiperceivable.com" repository = "https://github.com/aiperceivable/apcore-surfaces" -documentation = "https://apcore.aiperceivable.com/" +documentation = "https://aiperceivable.github.io/apcore-surfaces/mcp/" keywords = ["ai", "llm", "mcp", "apcore", "tools"] categories = [ "api-bindings", diff --git a/mcp/rust/README.md b/mcp/rust/README.md index 6a42155d..c2a970ff 100644 --- a/mcp/rust/README.md +++ b/mcp/rust/README.md @@ -59,9 +59,11 @@ for process and platform boundaries. apcore-mcp --from-openapi ./openapi.yaml --openapi-base-url https://api.example.com ``` -For compiled Rust modules, build a host using the APCore registry. The -`--extensions-dir` directory backend starts with an empty registry and emits a -diagnostic on stderr. When both flags are present, only OpenAPI supplies modules. +For compiled Rust modules, register them in the host and pass a `Registry` or +`Executor` to the MCP builder. The standalone Rust CLI rejects `--extensions-dir`. +When using the Core `macros` feature, register the `ModulePack` with `pack.register(&core)?` +and supply `.backend(core.executor_arc())`. See the +[Core Golden Path](https://github.com/aiperceivable/apcore/blob/main/examples/rust/golden-path/verify.rs). ### Programmatic approach (Rust API) @@ -216,7 +218,7 @@ apcore-mcp --from-openapi SPEC [OPTIONS] | Option | Default | Description | |--------|---------|-------------| | `--from-openapi` | — | OpenAPI file or URL for a standalone backend | -| `--extensions-dir` | — | Compatibility directory backend that starts with an empty registry | +| `--extensions-dir` | — | Unsupported in the standalone Rust CLI | | `--transport` | `stdio` | Transport: `stdio`, `streamable-http`, or `sse` | | `--host` | `127.0.0.1` | Host for HTTP-based transports | | `--port` | `8000` | Port for HTTP-based transports (1-65535) | diff --git a/mcp/rust/src/adapters/approval.rs b/mcp/rust/src/adapters/approval.rs index d70de16e..799fa43d 100644 --- a/mcp/rust/src/adapters/approval.rs +++ b/mcp/rust/src/adapters/approval.rs @@ -9,7 +9,9 @@ use std::sync::Arc; use apcore::approval::{ApprovalHandler, ApprovalRequest, ApprovalResult}; use apcore::errors::ModuleError; +use apcore::{Context, ElicitationResult, ErrorCode}; use async_trait::async_trait; +use futures::FutureExt; use sha2::{Digest, Sha256}; use uuid::Uuid; @@ -17,7 +19,7 @@ use crate::approval_store::{ ApprovalPrincipal, ApprovalRecord, ApprovalScope, ApprovalStatus, ApprovalStore, ApprovalVerifier, }; -use crate::helpers::{ElicitAction, ElicitCallback, MCP_ELICIT_CALL_ID_KEY}; +use crate::helpers::{ElicitAction, ElicitCallback, ElicitResult, MCP_ELICIT_CALL_ID_KEY}; use crate::server::elicit_registry::{self, SharedElicitCallback}; /// Handles user approval requests via MCP elicitation. @@ -25,31 +27,10 @@ use crate::server::elicit_registry::{self, SharedElicitCallback}; /// Implements the apcore [`ApprovalHandler`] contract by sending an elicitation /// prompt to the MCP client and interpreting the response. /// -/// # Lifecycle -/// -/// - `request_approval` — formats a human-readable message from the -/// [`ApprovalRequest`], invokes the resolved [`ElicitCallback`], and maps the -/// elicit response to an [`ApprovalResult`]. -/// -/// # Where the callback comes from -/// -/// Two sources, tried in order: -/// -/// 1. **The live request.** The router registers the connection's callback per -/// tool call and writes its id into `Context.data` under -/// [`MCP_ELICIT_CALL_ID_KEY`]; this handler exchanges the id for the -/// callback. This is the path that makes a handler constructed *outside* -/// the router — by a CLI entry point that never sees a session — able to -/// prompt a real client (apexe#29). -/// 2. **The constructor.** An [`ElicitCallback`] passed to [`Self::new`] is -/// used when the request carries no id, which keeps every embedding that -/// injected its own callback working unchanged. -/// -/// With neither, the request is rejected — the correct fail-closed outcome for -/// a client that never declared elicitation support. -/// - `check_approval` — always returns "rejected" because Phase B (async -/// polling of pending approvals) is not supported via stateless MCP -/// elicitation. +/// The Core request context supplies the primary elicitation handler. If it has +/// no handler, the adapter resolves the request-local MCP session callback and +/// then the constructor callback. Approval requests with no available callback +/// are rejected. Stateless MCP elicitation does not support polling. pub struct ElicitationApprovalHandler { elicit: Option, } @@ -57,14 +38,42 @@ pub struct ElicitationApprovalHandler { impl ElicitationApprovalHandler { /// Create a new approval handler with an optional elicit callback. /// - /// `None` is the normal construction for a server whose callback is only - /// known per request: the handler then resolves the live one from - /// [`MCP_ELICIT_CALL_ID_KEY`] in the request context. It rejects only when - /// that lookup also comes up empty, which means the connected client - /// declared no elicitation support. + /// `None` is appropriate when the live request supplies the callback. + /// The explicit callback is a fallback for older embeddings. pub fn new(elicit: Option) -> Self { Self { elicit } } + /// Resolve the session callback used by older embeddings. Release the + /// context data lock before looking up the callback or awaiting it. + async fn elicit_legacy( + &self, + context: &Context, + message: String, + ) -> Result { + let call_id = context + .data + .read() + .get(MCP_ELICIT_CALL_ID_KEY) + .and_then(|value| value.as_str()) + .map(str::to_owned); + let session_callback: Option = + call_id.and_then(|id| elicit_registry::lookup(&id)); + let callback = session_callback + .as_deref() + .or(self.elicit.as_ref()) + .ok_or("No elicitation callback available")?; + + match std::panic::AssertUnwindSafe(async { + callback(message, Some(approval_schema())).await + }) + .catch_unwind() + .await + { + Ok(Some(result)) => Ok(result), + Ok(None) => Err("Elicitation returned no response"), + Err(_) => Err("Elicitation request failed"), + } + } } impl fmt::Debug for ElicitationApprovalHandler { @@ -138,71 +147,9 @@ impl ApprovalHandler for ElicitationApprovalHandler { &self, request: &ApprovalRequest, ) -> Result { - // [D10-002] Return type kept as `Result` for - // idiomatic Rust. All error paths return `Ok(rejected(...))` so callers - // always receive an `ApprovalResult` for the elicitation surface; no `Err` - // is returned from the elicitation logic itself. [D10-002] - - // [D10-005] "No context available for elicitation" rejection branch — - // matches the Python/TS path where `request.context` is absent. - // Rust previously only fired this branch when BOTH context and - // elicit were missing, which made the callback fire even on - // context-less requests if a constructor-injected callback was - // present. The handler must NEVER invoke elicitation without a - // context attached to the request because the elicitation - // surface is security-gated and the calling identity is carried - // by `request.context`. Reject unconditionally whenever context - // is None. let Some(context) = request.context.as_ref() else { - tracing::debug!("no context attached to approval request, rejecting"); return Ok(rejected("No context available for elicitation")); }; - - // [D10-001] apcore-python and apcore-typescript extract the callback - // per call from `request.context.data[MCP_ELICIT_KEY]`, which they can - // do because their context data holds arbitrary objects. Rust's is - // `HashMap` and no closure is a `Value`, so - // this SDK used to be able to read only the marker string - // `"available"` — it knew elicitation existed and had no way to - // perform one, and rejected every gated call on any server whose - // handler was built outside the router (apexe#29). - // - // The id under `MCP_ELICIT_CALL_ID_KEY` closes that gap: it IS a - // `Value`, and the registry exchanges it for the live callback the - // router registered for this very call. Same per-request resolution as - // the peer SDKs, one indirection wider. [D10-001] - let resolved: Option = { - // Scoped so the read guard is released before the `.await` below — - // apcore's `Context.data` lock must never be held across one. - let data = context.data.read(); - data.get(MCP_ELICIT_CALL_ID_KEY) - .and_then(|v| v.as_str()) - .map(str::to_owned) - } - .and_then(|call_id| { - let found = elicit_registry::lookup(&call_id); - if found.is_none() { - // The id outlived its guard: the tool call that registered it - // has already returned. Fall through to `self.elicit` rather - // than failing outright. - tracing::debug!(%call_id, "elicit call id no longer registered"); - } - found - }); - - // Live request first, constructor-injected fallback second, reject - // third. - let elicit: &ElicitCallback = match resolved.as_deref() { - Some(cb) => cb, - None => match &self.elicit { - Some(cb) => cb, - None => { - tracing::debug!("no elicitation callback available, rejecting approval"); - return Ok(rejected("No elicitation callback available")); - } - }, - }; - let message = format!( "Approval required for tool: {}\n\n{}\n\nArguments: {}", request.module_id, @@ -210,28 +157,32 @@ impl ApprovalHandler for ElicitationApprovalHandler { request.arguments, ); - // [AH-3] Catch panics from the elicit callback so a buggy - // implementation can't bring down the approval task. Mirrors - // Python (try/except) and TypeScript (try/catch) which both - // degrade to `rejected("Elicitation request failed")` on error. - // futures::FutureExt::catch_unwind handles async panics across - // .await points; std::panic::catch_unwind cannot. - use futures::FutureExt; - // Send a non-empty schema so form-rendering clients can display an - // approve/deny control; an empty schema is silently dropped by them. - let result_outcome = std::panic::AssertUnwindSafe(elicit(message, Some(approval_schema()))) - .catch_unwind() - .await; - let result = match result_outcome { - Ok(Some(r)) => r, - Ok(None) => { - tracing::debug!("elicitation returned no response"); - return Ok(rejected("Elicitation returned no response")); + let native_result = + std::panic::AssertUnwindSafe(context.elicit(&message, approval_schema())) + .catch_unwind() + .await; + let result = match native_result { + Ok(Ok(Some(ElicitationResult::Accept { content }))) => ElicitResult { + action: ElicitAction::Accept, + content: Some(serde_json::Value::Object(content)), + }, + Ok(Ok(Some(ElicitationResult::Decline))) => { + return Ok(rejected("User action: decline")) } - Err(_panic) => { - tracing::debug!("elicit callback panicked"); - return Ok(rejected("Elicitation request failed")); + Ok(Ok(Some(ElicitationResult::Cancel))) => return Ok(rejected("User action: cancel")), + Ok(Ok(None)) => match self.elicit_legacy(context, message).await { + Ok(result) => result, + Err(reason) => return Ok(rejected(reason)), + }, + Ok(Err(error)) + if matches!( + error.code, + ErrorCode::ExecutionCancelled | ErrorCode::ModuleTimeout + ) => + { + return Err(error); } + Ok(Err(_)) | Err(_) => return Ok(rejected("Elicitation request failed")), }; match result.action { @@ -946,6 +897,42 @@ mod tests { assert!(result.reason.is_none()); } + #[tokio::test] + async fn native_elicitation_precedes_the_legacy_fallback() { + let handler = ElicitationApprovalHandler::new(Some(mock_elicit(ElicitAction::Decline))); + let mut request = test_request(); + request.context = request.context.as_ref().map(|ctx| { + ctx.with_elicitation_handler(Some(Arc::new(|prompt| { + Box::pin(async move { + assert!(prompt.message.contains("test.dangerous_tool")); + assert_eq!( + prompt.requested_schema.unwrap()["properties"]["approve"]["type"], + "boolean" + ); + Ok(apcore::ElicitationResult::Accept { + content: serde_json::Map::from_iter([("approve".into(), json!(true))]), + }) + }) + }))) + }); + let result = handler.request_approval(&request).await.unwrap(); + assert_eq!(result.status, "approved"); + } + + #[tokio::test] + async fn native_elicitation_error_does_not_fall_back_to_another_prompt() { + let handler = ElicitationApprovalHandler::new(Some(mock_elicit(ElicitAction::Accept))); + let mut request = test_request(); + request.context = request.context.as_ref().map(|ctx| { + ctx.with_elicitation_handler(Some(Arc::new(|_| { + Box::pin(async { Err(ModuleError::invalid_input("protected error detail")) }) + }))) + }); + let result = handler.request_approval(&request).await.unwrap(); + assert_eq!(result.status, "rejected"); + assert_eq!(result.reason.as_deref(), Some("Elicitation request failed")); + } + #[tokio::test] async fn test_request_approval_sends_nonempty_schema() { // The approval elicitation must carry a non-empty object schema; an diff --git a/mcp/rust/src/apcore_mcp.rs b/mcp/rust/src/apcore_mcp.rs index 585eda74..31042e14 100644 --- a/mcp/rust/src/apcore_mcp.rs +++ b/mcp/rust/src/apcore_mcp.rs @@ -35,19 +35,16 @@ use crate::server::types::{InitializationOptions, Tool}; /// # Examples /// /// ``` +/// use apcore::registry::registry::Registry; /// use apcore_mcp::apcore_mcp::BackendSource; -/// use std::path::PathBuf; +/// use std::sync::Arc; /// -/// // From a string path -/// let source: BackendSource = "./extensions".into(); -/// -/// // From a PathBuf -/// let source: BackendSource = PathBuf::from("./extensions").into(); +/// let source: BackendSource = Arc::new(Registry::new()).into(); /// ``` #[derive(Debug)] pub enum BackendSource { - /// Path to an extensions directory. A [`Registry`] will be created - /// and [`discover()`](Registry::discover) called automatically. + /// Legacy directory input. Builders reject it because Rust modules must + /// be registered in a compiled host. ExtensionsDir(PathBuf), /// A pre-built [`Registry`] instance. Registry(Arc), @@ -1829,18 +1826,12 @@ impl APCoreMCPBuilder { let (standalone_registry, mut executor) = match backend { BackendSource::ExtensionsDir(path) => { - tracing::warn!( - "--extensions-dir loads no Rust modules from '{}'. \ - Pass a compiled registry or executor to serve native modules, \ + return Err(APCoreMCPError::BackendResolution(format!( + "Rust directory discovery is unsupported for '{}'. \ + Pass a compiled registry or executor with a ModulePack, \ or use --from-openapi for the standalone server.", path.display() - ); - let registry = Arc::new(Registry::new()); - let executor = Arc::new(Executor::new( - Arc::clone(®istry), - apcore::config::Config::default(), - )); - (Some(registry), executor) + ))); } BackendSource::Registry(reg) => { // [L-1] `Executor::new` accepts `impl Into>`, and @@ -4088,11 +4079,11 @@ mod tests { // Escape form keeps this source file ASCII-only (apdev check-chars). let name: String = "\u{670D}".repeat(100); assert_eq!(name.len(), 300, "fixture must be multi-byte"); - let result = APCoreMCP::builder().backend("./ext").name(&name).build(); - assert!( - !matches!(result, Err(APCoreMCPError::NameTooLong(_))), - "a 100-character name is within the 255-character limit" - ); + APCoreMCP::builder() + .backend(Arc::new(Registry::new())) + .name(&name) + .build() + .expect("a 100-character name is within the 255-character limit"); } #[test] @@ -4170,14 +4161,15 @@ mod tests { } #[test] - fn builder_with_extensions_dir_builds_empty_backend() { - // [L-1] ExtensionsDir cannot load compiled-in Rust modules at runtime; - // it builds an empty backend with a warning rather than erroring. - let mcp = APCoreMCP::builder() - .backend("./nonexistent-extensions") - .build() - .expect("ExtensionsDir must build an empty backend"); - assert!(mcp.tools().is_empty()); + fn builder_rejects_unsupported_extensions_dir_backend() { + let dir = tempfile::tempdir().unwrap(); + let result = APCoreMCP::builder().backend(dir.path().to_owned()).build(); + match result { + Err(APCoreMCPError::BackendResolution(message)) => { + assert!(message.contains("compiled registry")); + } + _ => panic!("an extensions path cannot supply native Rust modules"), + } } #[test] diff --git a/mcp/rust/src/artifact_wire_tests.rs b/mcp/rust/src/artifact_wire_tests.rs index 9461067b..8c9525b3 100644 --- a/mcp/rust/src/artifact_wire_tests.rs +++ b/mcp/rust/src/artifact_wire_tests.rs @@ -11,6 +11,7 @@ use crate::{APCoreMCP, MCPArtifactStore, AUTH_IDENTITY}; struct ArtifactModule { key: String, sensitive_key: String, + canonical: bool, } #[async_trait] @@ -20,6 +21,13 @@ impl Module for ArtifactModule { } fn output_schema(&self) -> Value { + if self.canonical { + return json!({"type":"object","properties": { + "artifact": {"x-mcp-artifact":true, "x-artifact-ref":true}, + "duplicate": {"x-mcp-artifact":true, "x-artifact-ref":true}, + "sensitive": {"x-mcp-artifact":true, "x-artifact-ref":true, "x-sensitive":true} + }}); + } json!({"type":"object","properties": { "artifact": {"type":"string", "x-mcp-artifact":true}, "duplicate": {"type":"string", "x-mcp-artifact":true}, @@ -37,6 +45,13 @@ impl Module for ArtifactModule { _inputs: Value, _context: &Context, ) -> Result { + if self.canonical { + return Ok(json!({ + "artifact": {"id": self.key, "media_type":"application/octet-stream", "size_bytes":3}, + "duplicate": {"id": self.key, "media_type":"application/octet-stream", "size_bytes":4}, + "sensitive": {"id": self.sensitive_key, "media_type":"application/octet-stream", "size_bytes":1} + })); + } Ok( json!({"artifact":self.key,"duplicate":self.key,"sensitive":self.sensitive_key,"url":"https://example.invalid/missing"}), ) @@ -71,6 +86,15 @@ async fn rpc( #[tokio::test] async fn artifact_links_use_the_live_resource_route_and_preserve_legacy_content() { + artifact_links_use_the_live_resource_route(false).await; +} + +#[tokio::test] +async fn canonical_artifact_links_match_current_store_metadata() { + artifact_links_use_the_live_resource_route(true).await; +} + +async fn artifact_links_use_the_live_resource_route(canonical: bool) { let store = Arc::new(MCPArtifactStore::default()); let caller = owner(vec!["reader".into()]); let key = store @@ -82,6 +106,20 @@ async fn artifact_links_use_the_live_resource_route_and_preserve_legacy_content( ) .unwrap(); let uri = format!("apcore-artifact://{key}"); + if canonical { + let reference = apcore::ArtifactRef::new(&key, "application/octet-stream", 3).unwrap(); + let content = apcore::read_artifact(store.as_ref(), &reference, &caller, Some(3)) + .await + .unwrap() + .unwrap(); + assert_eq!(content.content, [0, 255, 1]); + assert!( + apcore::read_artifact(store.as_ref(), &reference, &caller, Some(2)) + .await + .unwrap() + .is_none() + ); + } let sensitive_key = store .put(vec![42], "private.bin", "application/octet-stream", &caller) .unwrap(); @@ -92,6 +130,7 @@ async fn artifact_links_use_the_live_resource_route_and_preserve_legacy_content( Box::new(ArtifactModule { key: key.clone(), sensitive_key, + canonical, }), ) .unwrap(); @@ -110,7 +149,11 @@ async fn artifact_links_use_the_live_resource_route_and_preserve_legacy_content( 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); + if canonical { + assert_eq!(result["structuredContent"]["artifact"]["id"], key); + } else { + assert_eq!(result["structuredContent"]["artifact"], key); + } assert_eq!(result["content"][0]["type"], "text"); assert_eq!(result["content"].as_array().unwrap().len(), 2); assert_eq!( diff --git a/mcp/rust/src/artifacts.rs b/mcp/rust/src/artifacts.rs index 69e696c9..15a8d6af 100644 --- a/mcp/rust/src/artifacts.rs +++ b/mcp/rust/src/artifacts.rs @@ -4,7 +4,8 @@ use std::collections::HashMap; use std::sync::{Arc, LazyLock, Mutex}; use std::time::{Duration, Instant}; -use apcore::Identity; +use apcore::{ArtifactContent, ArtifactRef, ArtifactStore, Identity, ModuleError}; +use async_trait::async_trait; use regex::Regex; pub const ARTIFACT_URI_PREFIX: &str = "apcore-artifact://"; @@ -173,6 +174,34 @@ impl MCPArtifactStore { } } +#[async_trait] +impl ArtifactStore for MCPArtifactStore { + async fn read( + &self, + id: &str, + identity: &Identity, + max_bytes: u64, + ) -> Result, ModuleError> { + let Some(artifact) = self.read_uri(&format!("{ARTIFACT_URI_PREFIX}{id}"), Some(identity)) + else { + return Ok(None); + }; + let Ok(size) = u64::try_from(artifact.bytes.len()) else { + return Ok(None); + }; + if size > max_bytes { + return Ok(None); + } + let Ok(reference) = ArtifactRef::new(id, &artifact.mime_type, size) else { + return Ok(None); + }; + Ok(Some(ArtifactContent { + r#ref: reference, + content: artifact.bytes.clone(), + })) + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/mcp/rust/src/cli.rs b/mcp/rust/src/cli.rs index 3260f694..c5aa19ee 100644 --- a/mcp/rust/src/cli.rs +++ b/mcp/rust/src/cli.rs @@ -116,8 +116,7 @@ pub fn init_tracing(level: &LogLevel) { about = "Launch an MCP server that exposes apcore modules as tools." )] pub struct CliArgs { - /// Directory backend placeholder. Native Rust modules require a compiled host. - /// Use --from-openapi or mcp.openapi.spec for a standalone backend. + /// Unsupported on Rust. Native Rust modules require a compiled host. #[arg(long)] pub extensions_dir: Option, @@ -129,8 +128,7 @@ pub struct CliArgs { #[arg(long)] pub openapi_base_url: Option, - /// Prepended to every derived module ID. Required when combined with - /// --extensions-dir. + /// Prepended to every derived module ID. #[arg(long)] pub openapi_prefix: Option, @@ -329,45 +327,20 @@ fn parse_jwt_algorithm(alg: &str) -> jsonwebtoken::Algorithm { /// Validate CLI arguments beyond what clap enforces. /// -/// Backend-source rule: at least one of `--extensions-dir` / `--from-openapi` -/// is required, both are allowed, and combining them requires -/// `--openapi-prefix` so the two module-ID spaces cannot collide. A third -/// route — `mcp.openapi.spec` configured on the Config Bus alone, with -/// neither CLI flag — also counts (PRD F-054 Acceptance Criterion 1); -/// `APCoreMCPBuilder::build` resolves that case, so this function's own job -/// is only to not reject it before the builder ever sees it. +/// The standalone Rust CLI requires an OpenAPI spec from a flag or the Config Bus. fn validate_args(args: &CliArgs) -> Result<(), CliError> { - if args.extensions_dir.is_none() && args.from_openapi.is_none() { - let has_config_bus_openapi = crate::config::get_openapi_config().is_some(); - if !has_config_bus_openapi { - return Err(CliError::InvalidArgs( - "a backend source is required — pass --extensions-dir, --from-openapi, set \ - mcp.openapi.spec on the Config Bus, or combine them" - .to_string(), - )); - } - } - if args.extensions_dir.is_some() && args.from_openapi.is_some() && args.openapi_prefix.is_none() - { + if args.extensions_dir.is_some() { return Err(CliError::InvalidArgs( - "--openapi-prefix is required when --extensions-dir and --from-openapi are \ - combined, so the two module-ID spaces cannot collide" + "--extensions-dir is unsupported in Rust. Pass a compiled registry or executor \ + with a ModulePack in your host, or use --from-openapi or mcp.openapi.spec here." .to_string(), )); } - if let Some(ref dir) = args.extensions_dir { - if !dir.exists() { - return Err(CliError::InvalidArgs(format!( - "--extensions-dir '{}' does not exist", - dir.display() - ))); - } - if !dir.is_dir() { - return Err(CliError::InvalidArgs(format!( - "--extensions-dir '{}' is not a directory", - dir.display() - ))); - } + if args.from_openapi.is_none() && crate::config::get_openapi_config().is_none() { + return Err(CliError::InvalidArgs( + "a backend source is required. Pass --from-openapi or set mcp.openapi.spec." + .to_string(), + )); } for header in &args.openapi_header { if !header.contains(':') { @@ -465,24 +438,9 @@ async fn run_with_args(args: CliArgs) -> Result<(), CliError> { // Resolve server version. let version = args.version.unwrap_or_else(|| crate::VERSION.to_string()); - // Resolve the backend source. The union is assembled in a fixed order — - // extensions directory first, then OpenAPI operations — so a collision - // report names the OpenAPI side, which is the one the operator can - // rename with a prefix. Neither flag given: leave the builder's backend - // unset entirely and call `build_async` below, which resolves - // `mcp.openapi.spec` from the Config Bus alone (PRD F-054 Acceptance - // Criterion 1) — never a stand-in empty Registry, which would be - // mistaken for a second, explicit backend source and wrongly require - // `--openapi-prefix`. + // An explicit --from-openapi takes precedence over Config Bus resolution. let mut builder = crate::APCoreMCPBuilder::default(); if let Some(ref spec) = args.from_openapi { - if let Some(ref dir) = args.extensions_dir { - tracing::warn!( - "--extensions-dir loads no Rust modules from '{}'; \ - only the OpenAPI backend supplies modules.", - dir.display() - ); - } let base_registry = Arc::new(apcore::registry::registry::Registry::new()); let mut headers = std::collections::HashMap::new(); for raw in &args.openapi_header { @@ -508,7 +466,7 @@ async fn run_with_args(args: CliArgs) -> Result<(), CliError> { // takes the documented spec-fetch default, exactly as Python's and // TypeScript's CLIs do by omitting the argument. timeout_secs: 30.0, - has_other_backend_source: args.extensions_dir.is_some(), + has_other_backend_source: false, project_root: None, acknowledge_unapproved_writes: false, }; @@ -517,8 +475,6 @@ async fn run_with_args(args: CliArgs) -> Result<(), CliError> { .await .map_err(|e| CliError::StartupFailure(format!("{e}")))?; builder = builder.backend(registry); - } else if let Some(ref dir) = args.extensions_dir { - builder = builder.backend(dir.clone()); } let mut builder = builder @@ -565,10 +521,7 @@ async fn run_with_args(args: CliArgs) -> Result<(), CliError> { builder = builder.observability(true); } - // `build_async` (not `build`) so that "neither --extensions-dir nor - // --from-openapi" can still resolve mcp.openapi.spec from the Config Bus - // (PRD F-054 Acceptance Criterion 1) — validate_args only checked that - // the section EXISTS; build_async is what actually fetches and applies it. + // build_async fetches mcp.openapi.spec when no explicit backend was configured. let mcp = builder .build_async() .await @@ -955,22 +908,7 @@ mod tests { } #[test] - fn validate_args_extensions_dir_and_from_openapi_without_prefix_errors() { - let dir = tempfile::tempdir().unwrap(); - let args = parse_args(&[ - "apcore-mcp", - "--extensions-dir", - dir.path().to_str().unwrap(), - "--from-openapi", - "https://api.example.com/openapi.json", - ]) - .unwrap(); - let err = validate_args(&args).unwrap_err(); - assert!(err.to_string().contains("openapi-prefix is required")); - } - - #[test] - fn validate_args_extensions_dir_and_from_openapi_with_prefix_ok() { + fn validate_args_rejects_unsupported_extensions_dir_even_with_openapi() { let dir = tempfile::tempdir().unwrap(); let args = parse_args(&[ "apcore-mcp", @@ -982,7 +920,9 @@ mod tests { "petstore", ]) .unwrap(); - assert!(validate_args(&args).is_ok()); + let err = validate_args(&args).unwrap_err(); + assert_eq!(err.exit_code(), 1); + assert!(err.to_string().contains("compiled registry")); } #[test] @@ -1011,36 +951,26 @@ mod tests { } #[test] - fn validate_args_nonexistent_extensions_dir() { + fn validate_args_rejects_unsupported_extensions_dir() { + let dir = tempfile::tempdir().unwrap(); let args = parse_args(&[ "apcore-mcp", "--extensions-dir", - "/nonexistent/path/does/not/exist", + dir.path().to_str().unwrap(), ]) .unwrap(); let err = validate_args(&args).unwrap_err(); assert_eq!(err.exit_code(), 1); - assert!(err.to_string().contains("does not exist")); - } - - #[test] - fn validate_args_file_as_extensions_dir() { - let f = NamedTempFile::new().unwrap(); - let args = - parse_args(&["apcore-mcp", "--extensions-dir", f.path().to_str().unwrap()]).unwrap(); - let err = validate_args(&args).unwrap_err(); - assert_eq!(err.exit_code(), 1); - assert!(err.to_string().contains("not a directory")); + assert!(err.to_string().contains("compiled registry")); } #[test] fn validate_args_name_too_long() { let long_name = "x".repeat(256); - let dir = tempfile::tempdir().unwrap(); let args = parse_args(&[ "apcore-mcp", - "--extensions-dir", - dir.path().to_str().unwrap(), + "--from-openapi", + "https://api.example.com/openapi.json", "--name", &long_name, ]) @@ -1060,11 +990,10 @@ mod tests { // Escape form keeps this source file ASCII-only (apdev check-chars). let name: String = "\u{670D}".repeat(100); assert_eq!(name.len(), 300, "fixture must be multi-byte"); - let dir = tempfile::tempdir().unwrap(); let args = parse_args(&[ "apcore-mcp", - "--extensions-dir", - dir.path().to_str().unwrap(), + "--from-openapi", + "https://api.example.com/openapi.json", "--name", &name, ]) @@ -1072,18 +1001,6 @@ mod tests { validate_args(&args).expect("a 100-character name is within the limit"); } - #[test] - fn validate_args_valid() { - let dir = tempfile::tempdir().unwrap(); - let args = parse_args(&[ - "apcore-mcp", - "--extensions-dir", - dir.path().to_str().unwrap(), - ]) - .unwrap(); - assert!(validate_args(&args).is_ok()); - } - // ── resolve_jwt_key tests ───────────────────────────────────────── #[test] diff --git a/mcp/rust/src/server/factory.rs b/mcp/rust/src/server/factory.rs index c8bec6de..d31e6a21 100644 --- a/mcp/rust/src/server/factory.rs +++ b/mcp/rust/src/server/factory.rs @@ -11,6 +11,8 @@ use serde_json::Value; use apcore::module::ModuleAnnotations; use apcore::registry::{ModuleDescriptor, Registry}; +use apcore::{ArtifactRef, SchemaValidator}; +use apcore_toolkit::schema_utils::artifact_fields; use crate::adapters::annotations::{AnnotationMapper, McpAnnotations}; use crate::artifacts::{MCPArtifactStore, ARTIFACT_URI_PREFIX}; @@ -32,21 +34,29 @@ fn attach_artifact_links( 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 { + let (Some(values), Some(schema)) = (result.structured_content.as_ref(), schema) 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 { + let validator = SchemaValidator::new(); + for (name, definition) in artifact_fields(schema, "x-mcp-artifact") { + let value = &values[name]; + let reference = match definition { + Some(field) if validator.validate(value, field).valid => { + let Ok(reference) = serde_json::from_value::(value.clone()) else { + continue; + }; + Some(reference) + } + Some(_) => continue, + None => None, + }; + let Some(key) = reference + .as_ref() + .map(|r| r.id.as_str()) + .or_else(|| value.as_str()) + else { continue; }; if emitted.contains(key) { @@ -54,7 +64,13 @@ fn attach_artifact_links( } let uri = format!("{ARTIFACT_URI_PREFIX}{key}"); if let Some(artifact) = store.read_uri(&uri, identity.as_ref()) { - emitted.insert(key); + if reference.as_ref().is_some_and(|reference| { + reference.media_type != artifact.mime_type + || u64::try_from(artifact.bytes.len()) != Ok(reference.size_bytes) + }) { + continue; + } + emitted.insert(key.to_owned()); result.resource_links.push(ResourceLink { uri, name: artifact.name.clone(), diff --git a/mcp/rust/src/server/router.rs b/mcp/rust/src/server/router.rs index bfd5c5d9..b553fa8a 100644 --- a/mcp/rust/src/server/router.rs +++ b/mcp/rust/src/server/router.rs @@ -316,7 +316,10 @@ fn native_elicitation_handler( match reply.action { ElicitAction::Accept => match reply.content { Some(Value::Object(content)) => Ok(ElicitationResult::Accept { content }), - _ => Err(ModuleError::invalid_input( + None => Ok(ElicitationResult::Accept { + content: Default::default(), + }), + Some(_) => Err(ModuleError::invalid_input( "MCP elicitation accepted without object content", )), }, @@ -3339,6 +3342,29 @@ mod tests { assert_eq!(result.content.unwrap()["name"], "Alice"); } + #[tokio::test] + async fn test_native_elicitation_accepts_an_omitted_content_field() { + let session = Arc::new(MockSession { + result: ElicitResult { + action: crate::helpers::ElicitAction::Accept, + content: None, + }, + }); + let handler = native_elicitation_handler(session, CancelToken::new()); + let result = handler(apcore::ElicitationRequest { + message: "confirm?".to_string(), + requested_schema: None, + }) + .await + .unwrap(); + assert_eq!( + result, + apcore::ElicitationResult::Accept { + content: Default::default() + } + ); + } + // ================================================================== // Task 5: Non-streaming path tests // ================================================================== diff --git a/mcp/rust/tests/cli_integration.rs b/mcp/rust/tests/cli_integration.rs index dbe1c10f..a44ffd37 100644 --- a/mcp/rust/tests/cli_integration.rs +++ b/mcp/rust/tests/cli_integration.rs @@ -7,14 +7,39 @@ use std::process::Command; const CLI_BINARY: &str = env!("CARGO_BIN_EXE_apcore-mcp"); +fn write_openapi_spec(dir: &tempfile::TempDir) -> std::path::PathBuf { + let spec = dir.path().join("openapi.json"); + std::fs::write( + &spec, + serde_json::json!({ + "openapi": "3.0.3", + "info": {"title": "Test server", "version": "1.0.0"}, + "servers": [{"url": "https://api.example.com"}], + "paths": { + "/pets": { + "get": { + "operationId": "listPets", + "responses": {"200": {"description": "OK"}} + } + } + } + }) + .to_string(), + ) + .unwrap(); + spec +} + #[test] fn stdio_lifecycle_diagnostics_never_use_stdout() { use std::io::Write; use std::process::Stdio; let directory = tempfile::tempdir().unwrap(); + let spec = write_openapi_spec(&directory); let mut child = Command::new(CLI_BINARY) - .args(["--extensions-dir", directory.path().to_str().unwrap()]) + .arg("--from-openapi") + .arg(&spec) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) @@ -46,11 +71,6 @@ fn stdio_lifecycle_diagnostics_never_use_stdout() { response_ids.sort_unstable(); assert_eq!(response_ids, [1, 2, 3], "{stdout}"); let stderr = String::from_utf8(output.stderr).unwrap(); - assert!( - stderr.contains("--extensions-dir loads no Rust modules"), - "{stderr}" - ); - assert!(stderr.contains("compiled registry"), "{stderr}"); assert!(stderr.contains("Starting stdio transport"), "{stderr}"); assert!(stderr.contains("invalid JSON"), "{stderr}"); assert!(stderr.contains("EOF"), "{stderr}"); @@ -70,8 +90,8 @@ fn help_exits_zero() { let stdout = String::from_utf8_lossy(&output.stdout); assert!(output.stderr.is_empty()); assert!( - stdout.contains("extensions-dir"), - "help should mention --extensions-dir" + stdout.contains("from-openapi"), + "help should mention --from-openapi" ); assert!( stdout.contains("apcore-mcp"), @@ -81,11 +101,6 @@ fn help_exits_zero() { #[test] fn missing_backend_source_exits_nonzero() { - // Reversal: --extensions-dir is no longer clap-required (--from-openapi - // and mcp.openapi on the Config Bus both count now — PRD F-054 - // Acceptance Criterion 1), so clap itself accepts zero args. The - // backend-source rule moved into validate_args, which reports it as an - // InvalidArgs error (exit 1), not a clap parse error (exit 2). let output = Command::new(CLI_BINARY) .output() .expect("failed to run binary"); @@ -103,27 +118,30 @@ fn missing_backend_source_exits_nonzero() { } #[test] -fn nonexistent_extensions_dir_exits_one() { +fn unsupported_extensions_directory_exits_one() { + let dir = tempfile::tempdir().unwrap(); let output = Command::new(CLI_BINARY) - .args(["--extensions-dir", "/nonexistent/path/does/not/exist"]) + .arg("--extensions-dir") + .arg(dir.path()) .output() .expect("failed to run binary"); assert_eq!( output.status.code(), Some(1), - "expected exit 1 for nonexistent extensions dir" + "expected exit 1 for unsupported directory backend" ); + assert!(output.stdout.is_empty()); let stderr = String::from_utf8_lossy(&output.stderr); assert!( - stderr.contains("does not exist"), - "stderr should mention missing dir: {stderr}" + stderr.contains("--extensions-dir is unsupported in Rust"), + "stderr should explain the unsupported backend: {stderr}" ); } #[test] fn port_zero_exits_nonzero() { let output = Command::new(CLI_BINARY) - .args(["--extensions-dir", "/tmp", "--port", "0"]) + .args(["--from-openapi", "openapi.json", "--port", "0"]) .output() .expect("failed to run binary"); assert!( @@ -137,14 +155,8 @@ fn port_zero_exits_nonzero() { #[test] fn name_too_long_exits_one() { let long_name = "x".repeat(256); - let dir = tempfile::tempdir().unwrap(); let output = Command::new(CLI_BINARY) - .args([ - "--extensions-dir", - dir.path().to_str().unwrap(), - "--name", - &long_name, - ]) + .args(["--from-openapi", "openapi.json", "--name", &long_name]) .output() .expect("failed to run binary"); assert_eq!( @@ -152,15 +164,15 @@ fn name_too_long_exits_one() { Some(1), "expected exit 1 for name too long" ); + assert!(String::from_utf8_lossy(&output.stderr).contains("--name must be at most 255")); } #[test] fn jwt_key_file_nonexistent_exits_one() { - let dir = tempfile::tempdir().unwrap(); let output = Command::new(CLI_BINARY) .args([ - "--extensions-dir", - dir.path().to_str().unwrap(), + "--from-openapi", + "openapi.json", "--jwt-key-file", "/nonexistent/key.pem", ]) @@ -190,13 +202,11 @@ fn stdio_transport_answers_tools_list() { use std::process::Stdio; let dir = tempfile::tempdir().unwrap(); + let spec = write_openapi_spec(&dir); let mut child = Command::new(CLI_BINARY) - .args([ - "--extensions-dir", - dir.path().to_str().unwrap(), - "--transport", - "stdio", - ]) + .arg("--from-openapi") + .arg(&spec) + .args(["--transport", "stdio"]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) @@ -239,11 +249,12 @@ fn stdio_transport_answers_tools_list() { reply.get("error").is_none(), "tools/list returned an error: {reply}" ); + let tools = reply + .pointer("/result/tools") + .and_then(serde_json::Value::as_array) + .expect("tools/list response includes result.tools"); assert!( - reply - .pointer("/result/tools") - .and_then(|t| t.as_array()) - .is_some(), - "tools/list response has no result.tools array: {reply}" + tools.iter().any(|tool| tool["name"] == "list_pets"), + "{reply}" ); } diff --git a/mcp/typescript/src/artifacts.ts b/mcp/typescript/src/artifacts.ts index 6c17edf8..0eff3b11 100644 --- a/mcp/typescript/src/artifacts.ts +++ b/mcp/typescript/src/artifacts.ts @@ -1,9 +1,23 @@ import { randomUUID } from "node:crypto"; -import type { Identity } from "apcore-js"; +import type { ResourceLink } from "@modelcontextprotocol/sdk/types.js"; +import * as apcore from "apcore-js"; +import { jsonSchemaToTypeBox, SchemaValidator, type ArtifactRef, 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])/; +const ARTIFACT_ASSERTIONS = ["x-artifact-ref", "x-media-types", "x-max-bytes"]; +const SCHEMA_APPLICATORS = [ + "$ref", "$dynamicRef", "$recursiveRef", "allOf", "anyOf", "oneOf", "if", "then", "else", + "dependentSchemas", "dependencies", "patternProperties", +]; +const schemaValidator = new SchemaValidator(false); + +/** @internal A declaration captured from Core before the selected invocation runs. */ +export interface ArtifactOutputDeclaration { + readonly schema: Record; + isCurrent(): boolean; +} type ArtifactMetadata = { readonly name: string; readonly mimeType: string; readonly size: number }; type StoredArtifact = ArtifactMetadata & { @@ -96,3 +110,64 @@ export class MCPArtifactStore { return artifact.authority === authority(identity) ? artifact : null; } } + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function unambiguous(schema: Record): boolean { + return !schema["x-sensitive"] && !SCHEMA_APPLICATORS.some((key) => Object.hasOwn(schema, key)); +} + +/** @internal Resolve link metadata under the requesting identity without reading artifact bytes. */ +export function projectArtifactLinks( + store: MCPArtifactStore, + output: Record, + schema: Record, + identity: Identity, + declaration?: ArtifactOutputDeclaration, +): ResourceLink[] { + try { + if (declaration !== undefined && !declaration.isCurrent()) return []; + const root = declaration?.schema ?? schema; + if (root.type !== "object" || !unambiguous(root) || !isRecord(root.properties)) return []; + // A null reference denotes a separately declared legacy opaque ID. + const candidates = new Map(); + for (const [name, field] of Object.entries(root.properties)) { + if (!isRecord(field) || field["x-mcp-artifact"] !== true || !unambiguous(field) || !Object.hasOwn(output, name)) continue; + const value = output[name]; + let reference: ArtifactRef | null = null; + if (ARTIFACT_ASSERTIONS.some((key) => Object.hasOwn(field, key))) { + if (declaration === undefined || typeof apcore.parseArtifactRef !== "function" || + (field.type !== undefined && field.type !== "object") || !isRecord(value) || + !Object.keys(field).every((key) => key === "type" || key === "title" || key === "description" || key.startsWith("x-"))) { + continue; + } + const validationSchema = jsonSchemaToTypeBox({ type: "object", properties: { artifact: field }, required: ["artifact"] }); + if (!schemaValidator.validate({ artifact: value }, validationSchema).valid) continue; + reference = apcore.parseArtifactRef(value); + } else if (field.type !== "string") { + continue; + } + const id = reference?.id ?? value; + if (typeof id !== "string" || !artifactIdPattern.test(id)) continue; + const declarations = candidates.get(id); + if (declarations) declarations.push(reference); + else candidates.set(id, [reference]); + } + + const links: ResourceLink[] = []; + for (const [id, declarations] of candidates) { + const uri = ARTIFACT_URI_PREFIX + id; + const artifact = store.describe(uri, identity); + if (artifact !== null && declarations.some((reference) => reference === null || + (artifact.mimeType === reference.media_type && artifact.size === reference.size_bytes))) { + links.push({ type: "resource_link", uri, ...artifact }); + } + } + return declaration !== undefined && !declaration.isCurrent() ? [] : links; + } catch { + // The optional projection cannot change a completed tool result. + return []; + } +} diff --git a/mcp/typescript/src/server/factory.ts b/mcp/typescript/src/server/factory.ts index 88a34ad8..a2ab73d0 100644 --- a/mcp/typescript/src/server/factory.ts +++ b/mcp/typescript/src/server/factory.ts @@ -27,7 +27,7 @@ import type { ReadResourceResult, } from "@modelcontextprotocol/sdk/types.js"; -import { ARTIFACT_URI_PREFIX, type MCPArtifactStore } from "../artifacts.js"; +import { ARTIFACT_URI_PREFIX, projectArtifactLinks, type ArtifactOutputDeclaration, 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"; @@ -726,6 +726,7 @@ export class MCPServerFactory { const toolArgs = (args ?? {}) as Record; let responseTool = tool; + let artifactDeclaration: ArtifactOutputDeclaration | undefined; const elicitation = server.getClientCapabilities?.()?.elicitation; const canElicit = elicitation !== undefined && (elicitation.form !== undefined || elicitation.url === undefined); // Build HandleCallExtra from MCP SDK extra @@ -733,6 +734,7 @@ export class MCPServerFactory { onOutputDescriptor(descriptor) { responseTool = { ...tool, outputSchema: outputSchemaForTool(descriptor) }; }, + onArtifactDeclaration: this._artifactStore ? (declaration) => { artifactDeclaration = declaration; } : undefined, signal: extra?.signal, sendNotification: extra?.sendNotification ? (notification: Record) => @@ -842,30 +844,12 @@ export class MCPServerFactory { if (!supportsStructuredOutput(server, extra)) return result; const projected = addStructuredOutput(result, responseTool); - this.attachArtifactLinks(projected, responseTool); + if (this._artifactStore && identity && !projected.isError && projected.structuredContent && responseTool.outputSchema) { + projected.content.push(...projectArtifactLinks( + this._artifactStore, projected.structuredContent, responseTool.outputSchema, identity, artifactDeclaration, + )); + } 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 6c3a8c68..a9519187 100644 --- a/mcp/typescript/src/server/router.ts +++ b/mcp/typescript/src/server/router.ts @@ -15,6 +15,7 @@ import { CancelToken, InvalidInputError, isStreamingModule } from "apcore-js"; import { isApprovalResumeToken, supportsScopedCore } from "../adapters/approval.js"; import { confirmPendingApproval, runApprovalInvocation, type ApprovalReplyCapture } from "../approval-reply.js"; import type { Module } from "apcore-js"; +import type { ArtifactOutputDeclaration } from "../artifacts.js"; import { ErrorMapper } from "../adapters/errors.js"; import { ErrorCodes } from "../types.js"; import type { Executor, ModuleDescriptor, TextContentDict, McpErrorResponse, StreamCompletion, StreamExecution, StreamStepOutcome } from "../types.js"; @@ -131,6 +132,8 @@ export interface HandleCallExtra { approvalReply?: ApprovalReplyCapture; /** @internal Hand off the live Core schema only after a successful invocation. */ onOutputDescriptor?: (descriptor: ModuleDescriptor) => void; + /** @internal Opt in to the registration-bound artifact declaration. */ + onArtifactDeclaration?: (declaration: ArtifactOutputDeclaration) => void; /** MCP request cancellation, including transport disconnect. */ signal?: AbortSignal; sendNotification?: (notification: Record) => Promise; @@ -743,6 +746,17 @@ export class ExecutionRouter { } const generation = coreExecutor ? registry.publicGeneration?.(toolName) : undefined; + if (coreExecutor && identity !== null && extra?.onArtifactDeclaration && selectedModule != null) { + const supportedRegistry = registry as typeof registry & { + captureOutputDeclaration?(id: string): ArtifactOutputDeclaration | null; + }; + try { + const declaration = supportedRegistry.captureOutputDeclaration?.(toolName); + if (declaration) extra.onArtifactDeclaration(declaration); + } catch { + // Unsupported artifact declarations do not affect the tool invocation. + } + } const outputSchema = coreExecutor ? descriptor?.outputSchema ?? {} : undefined; const protectOutput = (output: unknown): Promise => { if (coreExecutor && (descriptor === null || selectedModule == null || diff --git a/mcp/typescript/tests/server/artifact-wire.test.ts b/mcp/typescript/tests/server/artifact-wire.test.ts index 1ba314ed..d4a54c38 100644 --- a/mcp/typescript/tests/server/artifact-wire.test.ts +++ b/mcp/typescript/tests/server/artifact-wire.test.ts @@ -3,77 +3,102 @@ 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 { ACL, createIdentity, Executor, Middleware, 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 }); +it.each(["legacy", "canonical", "size-mismatch", "media-mismatch", "over-limit", "downgrade", "ambiguous", "stale", "duplicate"])( + "only projects a valid guarded link over MCP (%s)", async (scenario) => { + const owner = createIdentity("owner", "agent", ["renderer"], {}, { issuer: "fixture" }); + const guest = createIdentity("guest", "agent", ["renderer"], {}, { issuer: "fixture" }); + const store = new MCPArtifactStore({ maxBytes: 100 }); + const contents = Buffer.from(scenario === "over-limit" ? "long-data" : "preview"); + const key = store.put(contents, { name: "preview.png", mimeType: "image/png", owner }); + const media_type = scenario === "media-mismatch" ? "image/jpeg" : "image/png"; + const size_bytes = scenario === "size-mismatch" || scenario === "duplicate" ? 8 : 7; + const reference = { id: key, media_type, size_bytes }; + const emitted = { + artifact: scenario === "legacy" ? key : reference, + ...(scenario === "duplicate" ? { duplicate: { ...reference, size_bytes: contents.length } } : {}), + }; + const finalOutput = scenario === "downgrade" ? { artifact: key } : scenario === "over-limit" + ? { artifact: { ...reference, size_bytes: contents.length } } : emitted; - 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 moduleId = "media.preview"; + const registry = new Registry(); + const canonicalField = { + ...(scenario === "downgrade" ? {} : { type: "object" }), + "x-mcp-artifact": true, "x-artifact-ref": true, "x-media-types": [media_type], "x-max-bytes": 8, + }; + const module = { + description: "Return a preview", + inputSchema: { type: "object", properties: {} }, + outputSchema: { + type: "object", + properties: { + artifact: scenario === "legacy" ? { type: "string", "x-mcp-artifact": true } : canonicalField, + ...(scenario === "duplicate" ? { duplicate: { ...canonicalField } } : {}), + }, + required: ["artifact"], + ...(scenario === "ambiguous" ? { allOf: [{}] } : {}), }, - }, - }); - 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 }); + execute: () => emitted, + }; + await registry.register(moduleId, module); + const acl = new ACL([{ + callers: ["@external"], targets: [moduleId], effect: "allow", description: "", + conditions: { roles: ["renderer"] }, + }], "deny"); + class FinalOutput extends Middleware { + override after() { + if (scenario === "stale") Object.assign(module.outputSchema, { description: "Changed after Core execution" }); + return finalOutput; + } + } + const executor = new Executor({ registry, acl }).use(new FinalOutput()); + const app = await asyncServe(executor 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())); - } -}); + const uri = "apcore-artifact://" + key; + const result = await reader.callTool({ name: moduleId, arguments: {} }); + expect(result.isError).not.toBe(true); + expect(result.structuredContent).toEqual(finalOutput); + const text = { type: "text", text: JSON.stringify(finalOutput) }; + const links = ["legacy", "canonical", "duplicate"].includes(scenario) + ? [{ type: "resource_link", uri, name: "preview.png", mimeType: "image/png", size: 7 }] : []; + expect(result.content).toEqual([text, ...links]); + expect((await reader.readResource({ uri })).contents).toEqual([ + { uri, blob: contents.toString("base64"), mimeType: "image/png" }, + ]); + authorization = "Bearer guest"; + expect((await reader.callTool({ name: moduleId, arguments: {} })).content).toEqual([text]); + 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/toolkit/python/pyproject.toml b/toolkit/python/pyproject.toml index 878e09a9..39bf6d1b 100644 --- a/toolkit/python/pyproject.toml +++ b/toolkit/python/pyproject.toml @@ -44,7 +44,7 @@ dev = [ [project.urls] Homepage = "https://aiperceivable.com" Repository = "https://github.com/aiperceivable/apcore-surfaces/tree/main/toolkit/python" -Documentation = "https://github.com/aiperceivable/apcore-toolkit-python#readme" +Documentation = "https://aiperceivable.github.io/apcore-surfaces/toolkit/" Issues = "https://github.com/aiperceivable/apcore-surfaces/issues" [tool.hatch.build.targets.wheel] diff --git a/toolkit/rust/Cargo.toml b/toolkit/rust/Cargo.toml index 57225c3e..8b45b93d 100644 --- a/toolkit/rust/Cargo.toml +++ b/toolkit/rust/Cargo.toml @@ -8,7 +8,7 @@ readme = "README.md" authors = ["aiperceivable "] homepage = "https://aiperceivable.com" repository = "https://github.com/aiperceivable/apcore-surfaces" -documentation = "https://github.com/aiperceivable/apcore-toolkit-rust#readme" +documentation = "https://aiperceivable.github.io/apcore-surfaces/toolkit/" keywords = ["apcore", "mcp", "scanner", "schema", "toolkit"] categories = [ "api-bindings", diff --git a/toolkit/rust/src/schema_utils.rs b/toolkit/rust/src/schema_utils.rs index 9ecf52b5..7dabe47a 100644 --- a/toolkit/rust/src/schema_utils.rs +++ b/toolkit/rust/src/schema_utils.rs @@ -7,6 +7,57 @@ use std::collections::HashMap; use serde_json::Value; +/// Find direct, non-sensitive output fields opted into an adapter's artifact links. +/// +/// A field's second value is its canonical reference declaration, when present. +/// Legacy fields must be strings. An ambiguous reference is never treated as +/// a legacy handle, even when its runtime value is a string. +#[must_use] +pub fn artifact_fields<'a>(schema: &'a Value, marker: &str) -> Vec<(&'a str, Option<&'a Value>)> { + const ASSERTIONS: [&str; 3] = ["x-artifact-ref", "x-media-types", "x-max-bytes"]; + const APPLICATORS: [&str; 12] = [ + "$ref", + "$dynamicRef", + "$recursiveRef", + "allOf", + "anyOf", + "oneOf", + "if", + "then", + "else", + "dependentSchemas", + "dependencies", + "patternProperties", + ]; + let direct = |value: &Value| { + value.is_object() + && matches!(value.get("x-sensitive"), None | Some(Value::Bool(false))) + && APPLICATORS.iter().all(|key| value.get(*key).is_none()) + }; + if schema["type"] != "object" || !direct(schema) { + return Vec::new(); + } + schema["properties"] + .as_object() + .into_iter() + .flatten() + .filter_map(|(name, field)| { + if !direct(field) || field[marker] != true { + return None; + } + if ASSERTIONS.iter().any(|key| field.get(*key).is_some()) { + let simple = field.as_object()?.keys().all(|key| { + key.starts_with("x-") + || matches!(key.as_str(), "type" | "title" | "description") + }); + return (simple && (field.get("type").is_none() || field["type"] == "object")) + .then_some((name.as_str(), Some(field))); + } + (field["type"] == "string").then_some((name.as_str(), None)) + }) + .collect() +} + /// Merge parameter descriptions into JSON Schema properties. /// /// By default, only fills in *missing* descriptions — existing ones are