# Feature Spec: Formal MCP Tool Contracts and Transport Boundary Refactor (AOP)

> **Purpose of this document**: Define an implementation-ready refactor that converts the current code-first tool surface into formally declared MCP tools with enforced contracts, authenticated role identity, deterministic retries, and transport parity guarantees.

---

## 1. Objectives

### 1.1 Must-Have Capabilities

- Define a single source of truth for each tool:
  - `name`
  - `description`
  - `input_schema`
  - `output_schema`
  - supported roles
  - bound handler
- Expose a real MCP server adapter that serves:
  - `tools/list`
  - `tools/call`
- Enforce authenticated role identity on every tool call.
- Preserve deterministic kernel guarantees:
  - schema validation
  - optimistic concurrency
  - lock/collision enforcement
  - gate/evidence behavior
  - atomic state writes
- Enforce idempotency for mutating tool calls using operation keys.
- Provide transport-agnostic clients for CLI/Supervisor with parity tests.
- Eliminate documentation drift by generating `tools.md` from tool registry artifacts.

### 1.2 Non-Goals

- No rewrite of core domain behavior in `AopKernel` methods.
- No change to feature workflow semantics.
- No provider-specific logic embedded into MCP deterministic handlers.

---

## 2. Current Risks to Resolve

1. Tool contracts are implicit in code and docs, not formal runtime artifacts.
2. Role authorization is policy-based but caller identity trust model is unspecified for transport calls.
3. Retry safety is not formally defined at MCP boundary.
4. RBAC ownership is split (policy and code/docs), enabling drift.
5. Protocol compatibility is not pinned to an MCP SDK/protocol version.

---

## 3. Architecture Decisions

### 3.1 Tool Registry as Contract Source

All MCP tool metadata MUST be loaded from a registry artifact and not from handwritten switch statements.

### 3.2 Authenticated Identity Model

`actor_type` and `actor_id` are claims, not trusted caller inputs.

- MCP MUST accept a signed session token per tool call.
- MCP MUST derive actor claims from the token payload.
- Any supplied actor fields that conflict with token claims MUST fail.
- `system` role tokens MUST be bootstrap-only and unavailable to worker sessions.

### 3.3 RBAC Precedence Model

RBAC authority is two-level:

1. Tool registry declares `supported_roles` (maximum allowed by implementation).
2. `policy.yaml.rbac` declares runtime allowlist.

Effective permissions are the intersection. Startup MUST fail if policy grants a role not in `supported_roles`.

### 3.4 Idempotency Model for Mutations

All mutating tools MUST require `operation_id`.

- If an operation with same `operation_id` and same canonical input repeats, MCP returns cached prior result.
- If `operation_id` is reused with different input, MCP returns `operation_id_reuse_mismatch`.
- Operation result ledger MUST be durable.

### 3.5 Hybrid Transport Rollout

`ToolClient` abstraction is mandatory:

- `InProcessToolClient` for tests/fallback.
- `McpToolClient` for production path.

Production default switches to MCP transport only after parity acceptance gates pass.

---

## 4. Canonical Artifacts

```text
agentic/
  orchestrator/
    tools/
      catalog.json
      schemas/
        input/
        output/
      errors.schema.json
      protocol.json
  runtime/
    operation-ledger/
      <run_id>.json
```

### 4.1 `catalog.json` Contract

Each tool entry MUST contain:

- `name`
- `description`
- `input_schema_ref`
- `output_schema_ref`
- `supported_roles`
- `handler_id`
- `mutating` (boolean)
- `requires_operation_id` (boolean; true when `mutating=true`)

### 4.2 `protocol.json` Contract

Must pin:

- MCP protocol version supported
- SDK package + version
- enabled transport modes (`stdio` required; others optional)

### 4.3 Error Envelope

All failures MUST return:

- `ok: false`
- `error.code`
- `error.message`
- `error.details`
- optional `evidence`

---

## 5. Runtime Components

1. `ToolRegistryLoader`

- loads registry
- validates uniqueness and schema refs

2. `ToolContractValidator`

- validates input pre-handler
- validates output post-handler

3. `TokenAuthVerifier`

- verifies signature and expiry
- extracts trusted actor claims

4. `ToolAuthorizer`

- applies intersection of registry roles and policy roles

5. `OperationLedger`

- writes and resolves idempotent operation outcomes for mutating calls

6. `KernelToolExecutor`

- maps `handler_id` to domain method call
- normalizes errors

7. `McpServerAdapter`

- implements protocol endpoints via registry/executor

---

## 6. Security and Identity Contract

### 6.1 Token Claims

Required claims:

- `run_id`
- `session_id`
- `actor_type`
- `actor_id`
- `issued_at`
- `expires_at`

Optional claims:

- `feature_scope` (for feature-limited workers)

### 6.2 Validation Rules

- expired token -> `unauthenticated`
- invalid signature -> `unauthenticated`
- actor claim mismatch -> `invalid_actor_claim`
- unauthorized role/tool -> `forbidden_tool_for_role`

### 6.3 Token Issuance

- Supervisor receives a run bootstrap credential at start.
- Supervisor issues/requests role-scoped session tokens for orchestrator/planner/builder/qa.
- Worker tokens MUST NOT carry `system` role.

---

## 7. Idempotency and Retry Contract

### 7.1 Mutating Tools

Mutating tools include at least:

- `feature.init`
- `feature.state_patch`
- `feature.log_append`
- `plan.submit`
- `plan.update`
- `repo.ensure_worktree`
- `repo.apply_patch`
- `gates.run`
- `qa.test_index_update`
- `locks.acquire`
- `locks.release`
- `feature.ready_to_merge`

### 7.2 Required Behavior

- all mutating requests include `operation_id`
- canonical request hash recorded with result
- duplicate identical request returns previous response
- duplicate mismatched request fails with stable error code

---

## 8. Protocol Compatibility and Versioning

### 8.1 Pinning Requirement

Implementation MUST pin and document:

- MCP protocol version
- SDK package/version
- transport implementation details

### 8.2 Compatibility Policy

- breaking contract/schema changes require version bump
- migration notes required for each breaking change
- previous minor version accepted during one deprecation window where feasible

---

## 9. Observability Contract

Every tool call MUST emit structured logs with:

- `run_id`
- `operation_id` (if mutating)
- `feature_id` (if applicable)
- `tool_name`
- `actor_type`
- `latency_ms`
- `result` (`ok|error`)
- `error_code` (if any)

Metrics MUST include:

- calls by tool/role
- failure rates by error code
- retry and idempotency hit rates

---

## 10. CLI and Supervisor Migration

### 10.1 CLI

- replace direct kernel calls with `ToolClient`
- add `--transport inprocess|mcp`
- default transition:
  - early phases: `inprocess`
  - post-parity: `mcp`

### 10.2 Supervisor

- replace direct `kernel.invoke(...)` with `ToolClient`
- preserve role firewall
- pass signed role token in MCP mode

---

## 11. Integrated Delivery Plan (Cross-Spec)

This plan coordinates this spec and `agentic_orchestrator_single_global_orchestrator_spec.md`.

### M10: Registry Foundation

- implement catalog + schemas + loader + generator
- bind existing handlers via `handler_id`

Exit gate:

- registry validates
- generated tools doc matches registry

### M11: Auth + Idempotency Core

- token verifier and role-claim enforcement
- operation ledger and mutating call idempotency

Exit gate:

- auth failure paths tested
- duplicate mutation calls are safe

### M12: MCP Adapter + Protocol Pin

- implement MCP adapter (`tools/list`, `tools/call`)
- pin protocol and sdk versions

Exit gate:

- protocol conformance tests pass

### M13: ToolClient Migration

- add in-process and MCP clients
- migrate CLI/Supervisor call paths

Exit gate:

- end-to-end runs on both transports

### M14-M17: Global Orchestrator Topology Refactor

- executed per global-orchestrator spec milestones

Exit gate:

- session topology invariants pass (`1 + 3N`)

### M18: Production Promotion

- default transport `mcp`
- maintain in-process fallback for tests/recovery only

Exit gate:

- parity suite green
- rollout checklist signed off

---

## 12. Testing and Verification

### 12.1 Contract Tests

- all tools have valid input/output schema
- no duplicate names/handler ids
- `tools/list` equals registry contents

### 12.2 Conformance Suite

Same scenario must pass via both transports for critical paths:

- init -> plan -> patch -> gates -> merge
- lock conflict and collision outcomes
- retried mutation calls
- crash/recovery flows

### 12.3 Security Tests

- token expiry/signature rejection
- role spoofing rejection
- system-role misuse rejection

---

## 13. Acceptance Criteria

1. Tool contracts are runtime-loaded from registry artifacts.
2. Every tool call is authenticated and role-derived from verified token claims.
3. Mutating tool calls are idempotent by `operation_id`.
4. MCP transport behavior is parity-verified against in-process transport.
5. RBAC enforcement follows defined intersection model without drift.
6. Protocol version and SDK version are pinned and validated in CI.
7. `tools.md` is generated from registry and no longer manually authored.

---

## 14. Risks and Mitigations

- Risk: added complexity from auth and idempotency layers.
  - Mitigation: isolate into dedicated components and exhaustively unit test.
- Risk: rollout instability from transport migration.
  - Mitigation: keep in-process fallback until M18 exit gate.
- Risk: schema churn causing breakages.
  - Mitigation: strict versioning and migration policy.
