Get Started

Capstone: Stateless Tool Ecosystem

A production agent system is a set of boundaries, not a pile of features. This capstone separates a readable in-process simulation from the protocol clients, authorization server, sandbox, and telemetry exporter a real deployment still needs.

120 minutesBuildPython (stdlib, in-process simulation)Free lesson

Learning Objectives

  • Compose tool calls, task-shaped results, delegated work, UI resources, authorization policy, and trace records into one flow.
  • Carry protocol version, client identity, and capabilities on every MCP request instead of relying on a connection session.
  • Discover a server before use and drive long work through the official Tasks extension.
  • Distinguish a protocol-shaped simulation from an MCP, A2A, OAuth, or OpenTelemetry implementation.
  • Map each simulated boundary to the production component that must replace it.
  • Keep AGENTS.mdan Agent Skill, runtime adapters, tools, and security policy in their correct roles.
  • Explain which claims can be verified from local output and which need live integration tests.

The Problem

Design a research-and-report system. A user asks for papers on agent protocols. The system searches a paper catalog, delegates summarization, generates a report, returns a UI resource, and records the path through the system.

That sentence hides several independent contracts:

  • a model-facing tool schema;
  • a stateless request envelope and server discovery contract;
  • a gateway decision for actor, scope, and tool identity;
  • a long-running operation contract;
  • a delegation protocol;
  • a host-to-app bridge;
  • trace propagation and export;
  • a reusable operating procedure.

code/main.py keeps those boundaries visible with ordinary Python functions and dictionaries. It does not open a transport, contact arXiv, perform OAuth, call an A2A server, render an MCP App, or export telemetry. This makes the control flow easy to inspect without presenting a simulation as a compliant service.

The Concept

Target architecture

The architecture is a conceptual composition of public protocol patterns. It is not a claim about the private internals of any product.

Target trace

In a real implementation, every hop propagates trace context. Span names and attributes must follow the OpenTelemetry semantic conventions supported by the chosen instrumentation version. A shared trace identifier alone does not prove correct parentage, export, or backend ingestion.

Current protocol surfaces

Use the method names defined by the current protocol, not names remembered from an older draft:

BoundaryCurrent surfaceWhat the capstone simulates
MCP discoveryMandatory server/discoverA direct function returning versions, capabilities, and server identity
MCP request contextVersion, capabilities, and client identity in every params._metaFresh request metadata passed to every simulated call
MCP tool calltools/callDirect Python function dispatch
MCP task pollingio.modelcontextprotocol/tasks with tasks/getA working handle followed by a completed task carrying its final result
A2A delegationSendMessage in gRPC and JSON-RPC; POST /message:send in HTTP+JSONOne nested span with no remote call or artificial delay
MCP App calling a server toolapp.callServerTool({ name, arguments })An HTML string with no live bridge
OAuth authorizationAuthorization server, protected-resource metadata, audience and scope validationStatic token lookup and scope membership
OpenTelemetrySDK, propagator, exporter, and collector or backendIn-memory span dictionaries

Protocol names are only the first layer. Production tests must exercise serialization, authentication failures, cancellation, timeouts, retries, and version compatibility across the real wire.

Stateless MCP changes the integration boundary

Revision 2026-07-28 removes protocol sessions and the initialize / notifications/initialized handshake. It also removes Mcp-Session-Id. Every request carries these namespaced _meta fields:

JSON
{
  "io.modelcontextprotocol/protocolVersion": "2026-07-28",
  "io.modelcontextprotocol/clientCapabilities": {
    "extensions": {
      "io.modelcontextprotocol/tasks": {}
    }
  },
  "io.modelcontextprotocol/clientInfo": {
    "name": "capstone-client",
    "version": "1.0.0"
  }
}

The server must implement server/discover. Ordinary results use resultType: "complete"; a task handle uses resultType: "task". Each result should identify the server in _meta.io.modelcontextprotocol/serverInfo.

The task extension has tasks/gettasks/updateand tasks/cancel. A tool may first return resultType: "task"; tasks/get itself returns resultType: "complete"and the completed Task contains the final result. The old tasks/result and tasks/list methods are not part of the current extension. A client must advertise io.modelcontextprotocol/tasks in the same request that may receive a task handle. If it does not, the server returns -32021 with requiredCapabilities shaped as the missing client-capability object, including extensions.io.modelcontextprotocol/tasks.

Security posture

The intended deployment uses defense in depth:

  • OAuth authorization with PKCE where the client type requires it;
  • resource and audience binding for issued access tokens;
  • gateway RBAC that checks the requested tool and scope;
  • upstream credentials held outside model-visible context;
  • a pinned or reviewed tool-description manifest;
  • a Rule of Two review for untrusted input, sensitive data, and consequential actions;
  • an execution sandbox whose filesystem, process, network, credential, and resource limits are enforced outside the skill.

The demo implements only static tokens, scope checks, and description hashes. It is useful for policy flow, not security validation.

Skills are procedure, not transport

An Agent Skill can tell the runtime how to perform the research workflow, which tool contracts to expect, what evidence to save, and when to stop. It cannot make an MCP server exist, establish A2A compatibility, grant scopes, or create a sandbox.

Ship the complete skill directory when the procedure references companion files. The flat artifact in this older capstone is a course blueprint, not evidence that a host preserves a portable bundle. Lessons 24 through 27 build and test the full bundle lifecycle.

Course artifact metadata is a local adapter

The course catalog and installer recognize flat files named skill-*.mdbut that is a repository convention rather than the portable Agent Skills package contract. Their minimal frontmatter parser reads only top-level keys. This lesson therefore keeps the portable identity fields and the course catalog fields at the same level:

YAML
---
name: ecosystem-blueprint
description: Produce a full Phase 13 ecosystem architecture for a product need.
version: "1.0.0"
phase: "13"
lesson: "23"
tags: [mcp, capstone, ecosystem, architecture, a2a, otel]
---

name and description are the portable identity fields. versionphaselessonand tags are course-specific catalog extensions. The course parser requires tags as an inline list so --tag capstone can match it.

A portable directory skill may use the optional metadata map for string-valued extension data. That does not make metadata interchangeable with this repository's catalog schema. If this flat file nests version or tags below metadatathe minimal parser skips those indented keys, the catalog records an empty version, and tag filtering cannot find the artifact. Production hosts should use a safe YAML parser and validate their own documented schema.

Simulation versus production

Layercode/main.pyProduction replacementRequired evidence
Discoveryserver_discover() plus static TOOLSserver/discover followed by cache-aware tools/listWire transcript, deterministic order, and schema validation
AuthenticationToken-keyed dictionaryOAuth authorization and resource server validationIssuer, audience, scope, expiry, and failure tests
AuthorizationScope membershipGateway policy bound to actor, tool, target, and tenantAllow and deny audit cases
SearchStatic paper fixturesSearch API or MCP serverSource provenance, ranking, and error tests
TasksLocal handle plus immediate tasks/getDurable io.modelcontextprotocol/tasks store with tasks/gettasks/updatetasks/canceland TTLState-transition, input, cancellation, and recovery tests
DelegationSleep plus nested spanA2A client and remote Agent CardContract, timeout, retry, and opacity tests
AppHTML string and URIMCP Apps resource and App bridgeCSP, permissions, tool-call, and browser tests
TelemetryIn-memory listOTel SDK and exporterCollector receipt and trace-parent assertions
SandboxNoneHost-enforced isolated executorEscape, egress, secret, and resource-limit tests

This table is the handoff boundary. A green local run validates the simulation only.

Phase 13 map

LessonsContribution
01-05Tool interfaces, calls, schemas, structured results, and deterministic validation
06-14Stateless MCP request envelopes, discovery, transports, resources, prompts, extensions, and Apps
15-18Poisoning defenses, OAuth, gateways, registries, and production authentication
19A2A message and task delegation
20OpenTelemetry GenAI trace design
21Model-provider routing
22Portable skill contract and runtime boundary

Build It

Run the in-process harness:

Terminal
cd phases/13-tools-and-protocols/23-capstone-tool-ecosystem
python3 code/main.py

Inspect five things:

  1. server/discover advertises revision 2026-07-28 and the Tasks extension.
  2. Alice can read and generate a report, while Bob's write-scoped call is denied.
  3. Every local span in one orchestrator run shares one trace identifier and records parent span identifiers.
  4. The report begins as a task handle. tasks/get returns a completed task whose final result contains text and a ui:// reference.
  5. The delegated writer remains opaque because the orchestrator records only the boundary span.
  6. No output claims a network connection, OAuth exchange, collector export, browser render, or sandbox execution occurred.

The script runs twice, so it produces two root traces. Audit entries are process-local and reset on the next run.

Use It

Promote one layer at a time:

  1. Replace server_discover() and the static tool list with real server/discover and tools/list calls. Send version, identity, and capabilities in every request.
  2. Replace static tokens with an authorization server and protected resource validation.
  3. Implement the io.modelcontextprotocol/tasks extension and test tasks/gettasks/updatetasks/canceltimeout, TTL, and restart recovery. Do not add tasks/result or tasks/list.
  4. Replace the delegation stub with an A2A client that resolves an Agent Card and sends a message.
  5. Build the App with the official SDK and call server tools through app.callServerTool.
  6. Export spans to a test collector and assert parentage at the receiver.
  7. Run tool and script execution inside the sandbox contract from Lesson 26.
  8. Package the procedure as a complete directory bundle and pass the Lesson 27 release gate.

Each promotion needs an integration test that crosses the new boundary. Do not delete the lower-level policy tests when the wire becomes real.

Ship It

This lesson produces outputs/skill-ecosystem-blueprint.mda legacy single-file course artifact. It asks for a one-page architecture covering primitives, security, delegation, telemetry, packaging, and the hardest operational risk. Its top-level catalog fields are exercised by the repository's real catalog and installer parsers.

Because it is not a directory bundle, it cannot carry references, scripts, assets, or eval fixtures. Use the package format from Lessons 22 and 24 through 27 when publishing a reusable skill outside this course.

Exercises

  1. Run code/main.py. Separate facts proven by the output from production claims that still need integration evidence.
  2. Add a second static backend and define the collision rule for two tools with the same name. Then replace both lists with real tools/list calls.
  3. Replace the writer stub with an A2A test server. Record the Agent Card, message request, timeout path, and returned artifact.
  4. Add a task store that survives a process restart. Prove a client can resume with tasks/getrespect pollIntervalMsand read the completed task's final result without tasks/result.
  5. Build a minimal MCP App and verify app.callServerTool in a browser with a restrictive CSP and explicit permissions.
  6. Export the simulated spans through an OTel SDK to a local collector. Assert receipt, trace identifiers, parentage, and error status.
  7. Write AGENTS.md for repository-wide maintenance rules and a separate skill bundle for the reusable research procedure. Explain why neither file grants tool authority.

Key Terms

TermWhat people sayWhat it actually means
Capstone"Everything wired together"A staged integration whose simulated and live boundaries remain explicit
Protocol-shaped simulation"It is basically MCP"Local data and calls that resemble a protocol without implementing its wire contract
Tasks extension"Long tool call"An optional io.modelcontextprotocol/tasks lifecycle with durable identity, polling, client input, final result, and cancellation semantics
Opacity boundary"The other agent handles it"The caller sees the declared interface and artifacts, not private reasoning or internal state
Runtime adapter"Skill integration"Host code that maps portable procedure to discovery, invocation, tools, policy, and context
Integration evidence"It passed"A transcript, artifact, or receiver-side observation proving the real boundary was crossed

Further Reading

Check what you learned

6 questions. Answer each one to see why.

Question 1 of 60 correct

What does a successful run of this lesson's stdlib harness prove?

The full code

Every file for this lesson. Copy it, run it, then change it.

main.py
"""Phase 13 Capstone - stateless in-process research-and-report simulation.

Several Phase 13 boundaries in one readable demo:
  - gateway-shaped static token lookup and RBAC
  - per-request protocol metadata and mandatory server discovery
  - local tool functions returning task-extension and ui-shaped data
  - A2A-shaped writer delegation represented by a nested span
  - in-memory trace dictionaries sharing one trace id
  - pinned-hash manifest guarding description mutations

This file does not implement an MCP or A2A transport, OAuth exchange, MCP App
bridge, telemetry exporter, or execution sandbox. Stdlib only.

Run: python code/main.py
"""

from __future__ import annotations

import hashlib
import json
import time
import uuid
from copy import deepcopy
from datetime import datetime, timezone


SPANS: list[dict] = []
TASKS: dict[str, dict] = {}

PROTOCOL_VERSION = "2026-07-28"
TASK_EXTENSION = "io.modelcontextprotocol/tasks"
SERVER_INFO = {"name": "research-simulator", "version": "1.0.0"}


def request_meta(*, tasks: bool = False) -> dict:
    extensions = {TASK_EXTENSION: {}} if tasks else {}
    return {
        "io.modelcontextprotocol/protocolVersion": PROTOCOL_VERSION,
        "io.modelcontextprotocol/clientCapabilities": {"extensions": extensions},
        "io.modelcontextprotocol/clientInfo": {
            "name": "capstone-client",
            "version": "1.0.0",
        },
    }


def _server_meta() -> dict:
    return {"io.modelcontextprotocol/serverInfo": deepcopy(SERVER_INFO)}


def complete_result(**fields: object) -> dict:
    return {"resultType": "complete", **fields, "_meta": _server_meta()}


def protocol_error(code: int, message: str, data: dict | None = None) -> dict:
    error = {"code": code, "message": message}
    if data is not None:
        error["data"] = data
    return {"error": error}


def validate_request_meta(meta: dict, *, require_tasks: bool = False) -> dict | None:
    if not isinstance(meta, dict):
        return protocol_error(-32602, "params._meta must be an object")
    requested = meta.get("io.modelcontextprotocol/protocolVersion")
    if not isinstance(requested, str):
        return protocol_error(-32602, "protocolVersion must be a string")
    if requested != PROTOCOL_VERSION:
        return protocol_error(
            -32022,
            "Unsupported protocol version",
            {"supported": [PROTOCOL_VERSION], "requested": requested},
        )
    capabilities = meta.get("io.modelcontextprotocol/clientCapabilities")
    if not isinstance(capabilities, dict):
        return protocol_error(-32602, "clientCapabilities must be an object")
    extensions = capabilities.get("extensions", {})
    if require_tasks and (
        not isinstance(extensions, dict) or TASK_EXTENSION not in extensions
    ):
        return protocol_error(
            -32021,
            "Missing required client capability",
            {
                "requiredCapabilities": {
                    "extensions": {TASK_EXTENSION: {}}
                }
            },
        )
    return None


def server_discover(meta: dict) -> dict:
    invalid = validate_request_meta(meta)
    if invalid:
        return invalid
    return complete_result(
        supportedVersions=[PROTOCOL_VERSION],
        capabilities={
            "tools": {"listChanged": False},
            "extensions": {TASK_EXTENSION: {}},
        },
        ttlMs=3_600_000,
        cacheScope="public",
    )


def _hex(n: int) -> str:
    return uuid.uuid4().hex[: n * 2]


def span(name: str, kind: str, trace_id: str | None, parent: str | None,
         attrs: dict) -> dict:
    tid = trace_id or _hex(16)
    sp = {"name": name, "kind": kind, "traceId": tid, "spanId": _hex(8),
          "parentSpanId": parent, "start": time.time_ns(), "attrs": attrs, "end": 0}
    SPANS.append(sp)
    return sp


def finish(sp: dict) -> None:
    sp["end"] = max(time.time_ns(), sp["start"] + 1)


TOOLS = [
    {"name": "arxiv_search", "description": "Use when the user searches arXiv by keyword."},
    {"name": "generate_report", "description": "Use when the user wants a full report."},
]

PAPERS = [
    {"arxiv_id": "2603.22489", "title": "Tool poisoning attacks on MCP deployments"},
    {"arxiv_id": "2604.01055", "title": "Agent-to-agent coordination benchmarks"},
    {"arxiv_id": "2603.30016", "title": "Long-running tool calls via Tasks"},
]

PINNED = {f"research::{t['name']}": hashlib.sha256(t["description"].encode()).hexdigest()
          for t in TOOLS}


def research_arxiv_search(args: dict) -> dict:
    q = args["query"].lower()
    hits = [p for p in PAPERS if q in p["title"].lower()]
    return complete_result(
        content=[{"type": "text", "text": json.dumps(hits)}],
        isError=False,
    )


def research_generate_report(args: dict, trace_id: str, parent: str) -> dict:
    task_id = f"tsk_{uuid.uuid4().hex[:10]}"
    sp = span("mcp.task.working", "INTERNAL", trace_id, parent,
              {"gen_ai.operation.name": "execute_tool", "mcp.task.id": task_id})
    a2a = span("a2a.SendMessage", "CLIENT", trace_id, sp["spanId"],
               {"a2a.peer": "writer-agent", "a2a.skill": "summarize_papers"})
    finish(a2a)
    finish(sp)
    html = (
        "<!doctype html><html><body>"
        "<h1>Agent-protocol arXiv report</h1><ul>"
        + "".join(f"<li>{p['arxiv_id']}: {p['title']}</li>" for p in PAPERS)
        + "</ul><script>/* A real MCP App bridge is intentionally absent. */</script></body></html>"
    )
    now = datetime.now(timezone.utc).isoformat()
    TASKS[task_id] = {
        "resultType": "complete",
        "taskId": task_id,
        "status": "completed",
        "createdAt": now,
        "lastUpdatedAt": now,
        "ttlMs": 900_000,
        "pollIntervalMs": 1_000,
        "result": complete_result(
            content=[
                {"type": "text", "text": "Report generated: 3 papers summarized."},
                {"type": "ui_resource", "uri": "ui://report/current"},
            ],
            ui={
                "resourceUri": "ui://report/current",
                "csp": {"default-src": "'self'"},
                "permissions": [],
            },
            html=html,
        ),
        "_meta": _server_meta(),
    }
    return {
        "resultType": "task",
        "taskId": task_id,
        "status": "working",
        "createdAt": now,
        "lastUpdatedAt": now,
        "ttlMs": 900_000,
        "pollIntervalMs": 1_000,
        "_meta": _server_meta(),
    }


def tasks_get(task_id: str, meta: dict) -> dict:
    invalid = validate_request_meta(meta, require_tasks=True)
    if invalid:
        return invalid
    if not isinstance(task_id, str):
        return protocol_error(-32602, "Unknown taskId")
    task = TASKS.get(task_id)
    if task is None:
        return protocol_error(-32602, "Unknown taskId")
    return deepcopy(task)


USERS = {
    "tok_alice": {"id": "alice", "scopes": {"research:read", "research:write"}},
    "tok_bob":   {"id": "bob",   "scopes": {"research:read"}},
}
REQUIRED_SCOPE = {"arxiv_search": "research:read",
                  "generate_report": "research:write"}

AUDIT: list[dict] = []


def pin_ok(tool_name: str, description: str) -> bool:
    return PINNED.get(f"research::{tool_name}") == hashlib.sha256(description.encode()).hexdigest()


def gateway_call(token: str, tool_name: str, args: dict,
                 trace_id: str, parent: str, meta: dict) -> dict:
    invalid = validate_request_meta(
        meta, require_tasks=tool_name == "generate_report"
    )
    if invalid:
        return invalid
    u = USERS.get(token)
    if not u:
        return {"error": "unauthenticated"}
    required = REQUIRED_SCOPE.get(tool_name)
    if required and required not in u["scopes"]:
        AUDIT.append({"user": u["id"], "tool": tool_name, "decision": "403"})
        return {"error": "insufficient_scope", "scope": required}
    tool = next((t for t in TOOLS if t["name"] == tool_name), None)
    if tool is None:
        return {"error": "unknown tool"}
    if not pin_ok(tool_name, tool["description"]):
        return {"error": "hash_mismatch"}
    sp = span("mcp.call", "CLIENT", trace_id, parent,
              {"gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": tool_name,
               "gateway.user": u["id"], "mcp.server": "research"})
    if tool_name == "arxiv_search":
        result = research_arxiv_search(args)
    else:
        result = research_generate_report(args, trace_id, sp["spanId"])
    finish(sp)
    AUDIT.append({"user": u["id"], "tool": tool_name, "decision": "allow"})
    return result


def orchestrator(token: str, user_query: str) -> dict:
    trace_id = _hex(16)
    root = span("agent.invoke_agent", "INTERNAL", trace_id, None,
                {"gen_ai.operation.name": "invoke_agent",
                 "gen_ai.agent.name": "research-orchestrator"})

    llm1 = span("llm.chat", "CLIENT", trace_id, root["spanId"],
                {"gen_ai.operation.name": "chat", "gen_ai.provider.name": "openai",
                 "gen_ai.request.model": "gpt-4o", "gen_ai.usage.input_tokens": 24})
    finish(llm1)

    search = gateway_call(token, "arxiv_search",
                          {"query": "agent"}, trace_id, root["spanId"],
                          request_meta())
    report = gateway_call(token, "generate_report",
                          {"format": "html"}, trace_id, root["spanId"],
                          request_meta(tasks=True))
    task = None
    if report.get("resultType") == "task":
        task = tasks_get(report["taskId"], request_meta(tasks=True))

    llm2 = span("llm.chat", "CLIENT", trace_id, root["spanId"],
                {"gen_ai.operation.name": "chat", "gen_ai.provider.name": "openai",
                 "gen_ai.request.model": "gpt-4o", "gen_ai.usage.output_tokens": 85})
    finish(llm2)

    finish(root)
    return {"trace_id": trace_id, "search": search, "report": report, "task": task}


def demo() -> None:
    print("=" * 72)
    print("PHASE 13 CAPSTONE - RESEARCH AND REPORT ECOSYSTEM")
    print("=" * 72)

    print("\n--- stateless server discovery ---")
    discovery = server_discover(request_meta())
    print(f"  protocol       : {discovery['supportedVersions'][0]}")
    print(f"  task extension : {TASK_EXTENSION in discovery['capabilities']['extensions']}")

    print("\n--- orchestrator run as alice (read+write) ---")
    out = orchestrator("tok_alice", "summarize the three most-cited 2026 arXiv papers")
    print(f"  trace id      : {out['trace_id']}")
    print(f"  search result : {out['search']['content'][0]['text']}")
    print(f"  report handle : {out['report']['taskId']} ({out['report']['status']})")
    print(f"  task status   : {out['task']['status']} via tasks/get")
    print(f"  ui bytes      : {len(out['task']['result']['html'])}")

    print("\n--- orchestrator run as bob (read only) ---")
    out = orchestrator("tok_bob", "generate a report")
    print(f"  generate_report -> {out['report']}")

    print("\n--- audit log ---")
    for row in AUDIT:
        print(f"  {row}")

    print("\n--- OTel GenAI spans ---")
    for sp in SPANS:
        dur_ms = round((sp['end'] - sp['start']) / 1_000_000, 2) if sp['end'] else 0
        parent = sp['parentSpanId'][:6] if sp['parentSpanId'] else "ROOT"
        print(f"  [{sp['traceId'][:6]}] {sp['name']:20s} {sp['kind']:8s} "
              f"parent={parent}  dur={dur_ms}ms")

    print("\n--- primitive coverage ---")
    covered = [
        "tool interface and direct function dispatch",
        "server/discover and per-request stateless metadata",
        "structured content dictionaries",
        "task-extension handle and tasks/get polling",
        "ui://-shaped resource reference",
        "description mutation detection with pinned hashes",
        "static-token scope and gateway policy simulation",
        "A2A-shaped opaque delegation boundary",
        "in-memory trace identifiers and parent span identifiers",
        "orchestrator routing between local operations",
    ]
    for c in covered:
        print(f"  + {c}")


if __name__ == "__main__":
    demo()
You've finished the free half of Tools & Protocols

Most people stop here. Don't be most people.

The next 22 lessons are where Phase 13 turns from understanding into ability: the harder builds, the production patterns and the quizzes that prove you've actually got it. Unlock the full AI Expert Masterclass: all 542 expert lessons, every line of code, every phase.

  1. 24Skill Discovery and Progressive Disclosure
  2. 25Skill Invocation and Routing
  3. 26Skill Permissions, Sandboxes, and Trust
  4. 27Skill Evals, Packaging, and Portability
  5. + 18 more in this phase, and 542 across the whole masterclass