Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions a2a/conformance/fixtures/error_mapping.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
4 changes: 2 additions & 2 deletions a2a/docs/features/adapters.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
8 changes: 5 additions & 3 deletions a2a/docs/features/server-core.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 24 additions & 5 deletions a2a/docs/spec/srs.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.

Expand All @@ -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

---
Expand Down Expand Up @@ -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 |
Expand Down Expand Up @@ -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 |
Expand Down
15 changes: 12 additions & 3 deletions a2a/docs/spec/tech-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand All @@ -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),
Expand Down Expand Up @@ -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<string, unknown>
toJsonRpcError(error): { code: number; message: string }
Expand Down Expand Up @@ -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 |
Expand Down Expand Up @@ -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 |
Expand Down
2 changes: 1 addition & 1 deletion a2a/python/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
16 changes: 10 additions & 6 deletions a2a/python/src/apcore_a2a/adapters/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)

Expand Down
72 changes: 44 additions & 28 deletions a2a/python/src/apcore_a2a/artifacts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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])?)*")
Expand All @@ -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"),
Expand Down Expand Up @@ -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)
Expand All @@ -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)

Expand Down
3 changes: 2 additions & 1 deletion a2a/python/src/apcore_a2a/server/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))

Expand Down
Loading
Loading