[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M739QSD6151MWJ07NFDHGMHM":3,"skill-same:01M739QSD6151MWJ07NFDHGMHM":59},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":37,"commitSha":38,"skillDirectory":39,"forksCount":40,"repositoryHtmlUrl":41,"repositoryHomepageUrl":6,"ownerHtmlUrl":42,"ownerBlogUrl":43,"ownerDescription":6,"updatedAt":44,"install":45,"resources":58},"01M739QSD6151MWJ07NFDHGMHM","implement-a2a-server",null,"Implement a JSON-RPC 2.0 A2A server with full task lifecycle management (submitted\u002Fworking\u002Fcompleted\u002Ffailed\u002Fcanceled\u002Finput-required), SSE streaming, and push notifications. Use when implementing an agent that participates in multi-agent A2A workflows, building a backend for an Agent Card, adding A2A protocol support to an existing agent or service, or deploying an agent that must interoperate with other A2A-compliant agents.","roohe\u002Fagentic-super-skills","roohe","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99054084?v=4","01M734WCDFP6RZVT5CNM00QR26","01M734WCE4BD0T4NZS5PCV9V5F",10,"MIT","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fimplement-a2a-server\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: implement-a2a-server\nlocale: caveman-lite\nsource_locale: en\nsource_commit: 82c77053\ntranslator: \"Julius Brussee homage — caveman\"\ntranslation_date: \"2026-04-24\"\ndescription: >\n  Implement a JSON-RPC 2.0 A2A server with full task lifecycle management\n  (submitted\u002Fworking\u002Fcompleted\u002Ffailed\u002Fcanceled\u002Finput-required), SSE streaming,\n  and push notifications. Use when implementing an agent that participates in\n  multi-agent A2A workflows, building a backend for an Agent Card, adding A2A\n  protocol support to an existing agent or service, or deploying an agent that\n  must interoperate with other A2A-compliant agents.\nlicense: MIT\nallowed-tools: Read Write Edit Bash Grep Glob WebFetch\nmetadata:\n  author: Philipp Thoss\n  version: \"1.0\"\n  domain: a2a-protocol\n  complexity: advanced\n  language: multi\n  tags: a2a, server, json-rpc, task-lifecycle, streaming, sse\n---\n\n# Implement A2A Server\n\nBuild a fully compliant A2A server that handles JSON-RPC 2.0 requests, manages task lifecycle states, supports SSE streaming for real-time updates, and serves an Agent Card for discovery.\n\n## When to Use\n\n- Implementing an agent that participates in multi-agent A2A workflows\n- Building a backend for an Agent Card designed with `design-a2a-agent-card`\n- Adding A2A protocol support to an existing agent or service\n- Creating a reference A2A server implementation for testing\n- Deploying an agent that must interoperate with other A2A-compliant agents\n\n## Inputs\n\n- **Required**: Agent Card (JSON) defining the agent's skills and capabilities\n- **Required**: Implementation language (TypeScript\u002FNode.js or Python)\n- **Required**: Task execution logic for each skill defined in the Agent Card\n- **Optional**: Push notification webhook support (`true` or `false`)\n- **Optional**: Persistent task store (in-memory, Redis, PostgreSQL)\n- **Optional**: Authentication middleware matching the Agent Card's auth scheme\n- **Optional**: Maximum concurrent tasks limit\n\n## Procedure\n\n### Step 1: Set Up Project with JSON-RPC 2.0 Handler\n\n1.1. Initialize the project with HTTP server and JSON-RPC parsing:\n\n**TypeScript:**\n\n```bash\nmkdir -p $PROJECT_NAME && cd $PROJECT_NAME\nnpm init -y\nnpm install express uuid\nnpm install -D typescript @types\u002Fnode @types\u002Fexpress tsx\n```\n\n**Python:**\n\n```bash\nmkdir -p $PROJECT_NAME && cd $PROJECT_NAME\npython -m venv .venv && source .venv\u002Fbin\u002Factivate\npip install fastapi uvicorn uuid6\n```\n\n1.2. Create the JSON-RPC 2.0 request handler:\n\n```typescript\ninterface JsonRpcRequest {\n  jsonrpc: \"2.0\";\n  id: string | number;\n  method: string;\n  params?: Record\u003Cstring, unknown>;\n}\n\ninterface JsonRpcResponse {\n  jsonrpc: \"2.0\";\n  id: string | number;\n  result?: unknown;\n  error?: { code: number; message: string; data?: unknown };\n}\n\nfunction handleJsonRpc(request: JsonRpcRequest): JsonRpcResponse {\n  switch (request.method) {\n    case \"tasks\u002Fsend\":\n      return handleTaskSend(request);\n    case \"tasks\u002Fget\":\n      return handleTaskGet(request);\n    case \"tasks\u002Fcancel\":\n      return handleTaskCancel(request);\n    case \"tasks\u002FsendSubscribe\":\n      \u002F\u002F Handled separately via SSE\n      throw new Error(\"Use SSE endpoint for sendSubscribe\");\n    default:\n      return {\n        jsonrpc: \"2.0\",\n        id: request.id,\n        error: { code: -32601, message: `Method not found: ${request.method}` },\n      };\n  }\n}\n```\n\n1.3. Mount the JSON-RPC handler on a POST endpoint (typically `\u002F`):\n\n```typescript\napp.post(\"\u002F\", (req, res) => {\n  const response = handleJsonRpc(req.body);\n  res.json(response);\n});\n```\n\n1.4. Serve the Agent Card at `\u002F.well-known\u002Fagent.json`:\n\n```typescript\napp.get(\"\u002F.well-known\u002Fagent.json\", (req, res) => {\n  res.json(agentCard);\n});\n```\n\n**Got:** An HTTP server that accepts JSON-RPC 2.0 requests and serves the Agent Card.\n\n**If fail:** If JSON-RPC parsing fails, validate that the request body has `jsonrpc`, `method`, and `id` fields. Return `-32700` (Parse error) for malformed JSON and `-32600` (Invalid Request) for missing required fields.\n\n### Step 2: Implement Task State Machine\n\n2.1. Define the task model with all A2A lifecycle states:\n\n```typescript\ntype TaskState =\n  | \"submitted\"\n  | \"working\"\n  | \"input-required\"\n  | \"completed\"\n  | \"failed\"\n  | \"canceled\";\n\ninterface Task {\n  id: string;\n  sessionId: string;\n  status: {\n    state: TaskState;\n    message?: Message;\n    timestamp: string;\n  };\n  history?: TaskStatus[];\n  artifacts?: Artifact[];\n  metadata?: Record\u003Cstring, unknown>;\n}\n\ninterface Message {\n  role: \"user\" | \"agent\";\n  parts: Part[];\n}\n\ntype Part =\n  | { type: \"text\"; text: string }\n  | { type: \"file\"; file: { name: string; mimeType: string; bytes?: string; uri?: string } }\n  | { type: \"data\"; data: Record\u003Cstring, unknown> };\n```\n\n2.2. Implement state transition rules:\n\n```\nsubmitted  -> working | failed | canceled\nworking    -> completed | failed | canceled | input-required\ninput-required -> working | failed | canceled\ncompleted  -> (terminal)\nfailed     -> (terminal)\ncanceled   -> (terminal)\n```\n\n2.3. Create a task store with CRUD operations:\n\n```typescript\nclass TaskStore {\n  private tasks: Map\u003Cstring, Task> = new Map();\n\n  create(sessionId: string, message: Message): Task { ... }\n  get(taskId: string): Task | undefined { ... }\n  updateStatus(taskId: string, state: TaskState, message?: Message): Task { ... }\n  addArtifact(taskId: string, artifact: Artifact): void { ... }\n  cancel(taskId: string): Task { ... }\n}\n```\n\n2.4. If `stateTransitionHistory` is enabled in the Agent Card, append each status change to the task's `history` array with timestamps.\n\n**Got:** A task store that enforces valid state transitions and maintains history.\n\n**If fail:** If an invalid state transition is attempted (e.g., `completed` to `working`), return a JSON-RPC error with code `-32002` and a descriptive message. Never silently ignore invalid transitions.\n\n### Step 3: Add tasks\u002Fsend and tasks\u002Fget Methods\n\n3.1. Implement `tasks\u002Fsend` — the primary method for submitting tasks:\n\n```typescript\nfunction handleTaskSend(request: JsonRpcRequest): JsonRpcResponse {\n  const { id: taskId, sessionId, message } = request.params as TaskSendParams;\n\n  \u002F\u002F Create or resume task\n  let task = taskStore.get(taskId);\n  if (!task) {\n    task = taskStore.create(sessionId, message);\n  } else if (task.status.state === \"input-required\") {\n    taskStore.updateStatus(task.id, \"working\");\n  }\n\n  \u002F\u002F Route to skill handler based on message content\n  const skill = matchSkill(message);\n  if (!skill) {\n    taskStore.updateStatus(task.id, \"failed\", {\n      role: \"agent\",\n      parts: [{ type: \"text\", text: \"No matching skill for this request.\" }],\n    });\n    return { jsonrpc: \"2.0\", id: request.id, result: taskStore.get(task.id) };\n  }\n\n  \u002F\u002F Execute skill (async — task will transition to working, then completed\u002Ffailed)\n  executeSkill(skill, task, message).catch((error) => {\n    taskStore.updateStatus(task.id, \"failed\", {\n      role: \"agent\",\n      parts: [{ type: \"text\", text: error.message }],\n    });\n  });\n\n  return { jsonrpc: \"2.0\", id: request.id, result: taskStore.get(task.id) };\n}\n```\n\n3.2. Implement `tasks\u002Fget` — retrieve task status and artifacts:\n\n```typescript\nfunction handleTaskGet(request: JsonRpcRequest): JsonRpcResponse {\n  const { id: taskId, historyLength } = request.params as TaskGetParams;\n  const task = taskStore.get(taskId);\n\n  if (!task) {\n    return {\n      jsonrpc: \"2.0\",\n      id: request.id,\n      error: { code: -32001, message: `Task not found: ${taskId}` },\n    };\n  }\n\n  \u002F\u002F Optionally trim history to requested length\n  const result = historyLength !== undefined\n    ? { ...task, history: task.history?.slice(-historyLength) }\n    : task;\n\n  return { jsonrpc: \"2.0\", id: request.id, result };\n}\n```\n\n3.3. Implement `tasks\u002Fcancel`:\n\n```typescript\nfunction handleTaskCancel(request: JsonRpcRequest): JsonRpcResponse {\n  const { id: taskId } = request.params as TaskCancelParams;\n  try {\n    const task = taskStore.cancel(taskId);\n    return { jsonrpc: \"2.0\", id: request.id, result: task };\n  } catch (error) {\n    return {\n      jsonrpc: \"2.0\",\n      id: request.id,\n      error: { code: -32002, message: (error as Error).message },\n    };\n  }\n}\n```\n\n**Got:** Working `tasks\u002Fsend`, `tasks\u002Fget`, and `tasks\u002Fcancel` methods that correctly manage task lifecycle.\n\n**If fail:** If skill matching fails, return the task in `failed` state with a descriptive message. If the task store is full, return `-32003` (resource exhausted).\n\n### Step 4: Implement SSE Streaming for tasks\u002FsendSubscribe\n\n4.1. Create an SSE endpoint for streaming task updates:\n\n```typescript\napp.post(\"\u002Fsubscribe\", (req, res) => {\n  const request = req.body as JsonRpcRequest;\n  if (request.method !== \"tasks\u002FsendSubscribe\") {\n    res.status(400).json({ error: \"Only tasks\u002FsendSubscribe supported\" });\n    return;\n  }\n\n  \u002F\u002F Set SSE headers\n  res.setHeader(\"Content-Type\", \"text\u002Fevent-stream\");\n  res.setHeader(\"Cache-Control\", \"no-cache\");\n  res.setHeader(\"Connection\", \"keep-alive\");\n\n  const { id: taskId, sessionId, message } = request.params as TaskSendParams;\n  let task = taskStore.get(taskId) ?? taskStore.create(sessionId, message);\n\n  \u002F\u002F Send initial status\n  sendSSEEvent(res, \"status\", {\n    id: request.id,\n    result: { id: task.id, status: task.status },\n  });\n\n  \u002F\u002F Subscribe to task updates\n  const unsubscribe = taskStore.onUpdate(task.id, (updatedTask) => {\n    if (updatedTask.status.state === \"working\") {\n      sendSSEEvent(res, \"status\", {\n        id: request.id,\n        result: { id: updatedTask.id, status: updatedTask.status },\n      });\n    }\n\n    if (updatedTask.artifacts?.length) {\n      sendSSEEvent(res, \"artifact\", {\n        id: request.id,\n        result: { id: updatedTask.id, artifact: updatedTask.artifacts.at(-1) },\n      });\n    }\n\n    \u002F\u002F Close stream on terminal states\n    if ([\"completed\", \"failed\", \"canceled\"].includes(updatedTask.status.state)) {\n      sendSSEEvent(res, \"status\", {\n        id: request.id,\n        result: { id: updatedTask.id, status: updatedTask.status, final: true },\n      });\n      unsubscribe();\n      res.end();\n    }\n  });\n\n  \u002F\u002F Handle client disconnect\n  req.on(\"close\", () => {\n    unsubscribe();\n  });\n});\n\nfunction sendSSEEvent(res: Response, event: string, data: unknown): void {\n  res.write(`event: ${event}\\ndata: ${JSON.stringify(data)}\\n\\n`);\n}\n```\n\n4.2. Add an event emitter or pub\u002Fsub mechanism to the task store:\n\n```typescript\nclass TaskStore {\n  private listeners: Map\u003Cstring, Set\u003C(task: Task) => void>> = new Map();\n\n  onUpdate(taskId: string, callback: (task: Task) => void): () => void {\n    if (!this.listeners.has(taskId)) {\n      this.listeners.set(taskId, new Set());\n    }\n    this.listeners.get(taskId)!.add(callback);\n    return () => this.listeners.get(taskId)?.delete(callback);\n  }\n\n  private notifyListeners(taskId: string): void {\n    const task = this.get(taskId);\n    if (task) {\n      this.listeners.get(taskId)?.forEach((cb) => cb(task));\n    }\n  }\n}\n```\n\n4.3. Emit events from all task state transitions and artifact additions.\n\n**Got:** SSE streaming that sends real-time status and artifact events as the task progresses.\n\n**If fail:** If SSE connection drops, the client should be able to reconnect and use `tasks\u002Fget` to retrieve the current state. Ensure the task store does not depend on active SSE connections.\n\n### Step 5: Add Push Notification Webhook Support\n\n5.1. If `pushNotifications` is enabled in the Agent Card, implement webhook registration via `tasks\u002FpushNotification\u002Fset`:\n   - Accept a `PushNotificationConfig` with `url` (HTTPS required), optional `token`, and `events` array (`[\"status\", \"artifact\"]`)\n   - Validate the webhook URL uses HTTPS; reject with error code `-32004` otherwise\n   - Store the config in the task store, keyed by task ID\n\n5.2. Send webhook callbacks on task state changes:\n   - On each state transition or artifact addition, check for a registered push config\n   - POST a JSON payload with `taskId`, `eventType`, `status`, and `timestamp` to the webhook URL\n   - Include `Authorization: Bearer \u003Ctoken>` header if a token was provided\n\n5.3. Implement retry logic for failed webhooks (exponential backoff, max 3 retries).\n\n5.4. Add `tasks\u002FpushNotification\u002Fget` to retrieve the current push config for a task.\n\n**Got:** Webhook registration and delivery with retry logic.\n\n**If fail:** Push notification failures must never affect task execution. Log errors and continue. If the webhook URL is persistently unreachable, remove the subscription after max retries.\n\n### Step 6: Integrate with Agent Card for Discovery\n\n6.1. Load and serve the Agent Card at startup:\n   - Parse `agent-card.json` and validate capabilities match implementation\n   - Throw at startup if the card advertises `streaming: true` but SSE is not enabled\n   - Throw at startup if the card advertises `pushNotifications: true` but webhooks are not enabled\n\n6.2. Add CORS headers for cross-origin Agent Card discovery:\n   - Set `Access-Control-Allow-Origin: *` on `\u002F.well-known\u002Fagent.json`\n   - Allow `GET` and `OPTIONS` methods\n\n6.3. Add authentication middleware matching the Agent Card's scheme:\n   - Skip authentication for `\u002F.well-known\u002Fagent.json` (Agent Card is always public)\n   - For all other endpoints, validate the `Authorization` header or API key\n   - Return HTTP 401 with JSON-RPC error code `-32000` for unauthorized requests\n\n6.4. Start the server and verify end-to-end:\n\n```bash\n# Start server\nnpm run dev\n\n# Fetch Agent Card\ncurl -s http:\u002F\u002Flocalhost:3000\u002F.well-known\u002Fagent.json | python3 -m json.tool\n\n# Send a task\ncurl -X POST http:\u002F\u002Flocalhost:3000\u002F \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tasks\u002Fsend\",\"params\":{\"id\":\"task-1\",\"sessionId\":\"session-1\",\"message\":{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"text\":\"Analyze my dataset\"}]}}}'\n```\n\n**Got:** A running A2A server that serves its Agent Card, accepts tasks, and manages their full lifecycle.\n\n**If fail:** If the Agent Card capabilities do not match the implementation, the startup validation from 6.1 will catch the mismatch. Fix the implementation or update the Agent Card to match.\n\n## Validation\n\n- [ ] Server starts and serves Agent Card at `\u002F.well-known\u002Fagent.json`\n- [ ] `tasks\u002Fsend` creates tasks and transitions them through the lifecycle\n- [ ] `tasks\u002Fget` retrieves task status and artifacts\n- [ ] `tasks\u002Fcancel` moves tasks to the canceled state\n- [ ] SSE streaming sends real-time status and artifact events (if enabled)\n- [ ] Push notifications deliver webhooks on state changes (if enabled)\n- [ ] Invalid state transitions return appropriate JSON-RPC errors\n- [ ] Authentication rejects unauthorized requests (if configured)\n- [ ] Agent Card capabilities accurately reflect server implementation\n- [ ] All JSON-RPC responses include `jsonrpc: \"2.0\"` and correct `id`\n\n## Pitfalls\n\n- **Missing JSON-RPC error codes**: The A2A protocol defines specific error codes. Use `-32700` (parse error), `-32600` (invalid request), `-32601` (method not found), and custom codes for domain errors.\n- **Task ID collisions**: Use UUIDs for task IDs. If the client provides an ID, validate uniqueness before creating the task.\n- **SSE connection leaks**: Clean up SSE subscriptions when the client disconnects. Use `req.on(\"close\")` to detect disconnects.\n- **Blocking skill execution**: Long-running skills must execute asynchronously. Return the task in `submitted` or `working` state immediately, then update via events.\n- **Agent Card drift**: If the server implementation changes but the Agent Card is not updated, clients will have incorrect expectations. Validate at startup.\n- **Ignoring terminal states**: Once a task reaches `completed`, `failed`, or `canceled`, no further state transitions are allowed. Guard against this in the state machine.\n\n## Related Skills\n\n- `design-a2a-agent-card` - design the Agent Card this server implements\n- `test-a2a-interop` - validate the server against A2A conformance tests\n- `build-custom-mcp-server` - MCP server patterns that inform A2A implementation\n- `scaffold-mcp-server` - scaffolding patterns applicable to A2A server setup\n- `configure-ingress-networking` - production deployment with TLS and routing\n","# Implement A2A Server\n\nBuild a fully compliant A2A server that handles JSON-RPC 2.0 requests, manages task lifecycle states, supports SSE streaming for real-time updates, and serves an Agent Card for discovery.\n\n## When to Use\n\n- Implementing an agent that participates in multi-agent A2A workflows\n- Building a backend for an Agent Card designed with `design-a2a-agent-card`\n- Adding A2A protocol support to an existing agent or service\n- Creating a reference A2A server implementation for testing\n- Deploying an agent that must interoperate with other A2A-compliant agents\n\n## Inputs\n\n- **Required**: Agent Card (JSON) defining the agent's skills and capabilities\n- **Required**: Implementation language (TypeScript\u002FNode.js or Python)\n- **Required**: Task execution logic for each skill defined in the Agent Card\n- **Optional**: Push notification webhook support (`true` or `false`)\n- **Optional**: Persistent task store (in-memory, Redis, PostgreSQL)\n- **Optional**: Authentication middleware matching the Agent Card's auth scheme\n- **Optional**: Maximum concurrent tasks limit\n\n## Procedure\n\n### Step 1: Set Up Project with JSON-RPC 2.0 Handler\n\n1.1. Initialize the project with HTTP server and JSON-RPC parsing:\n\n**TypeScript:**\n\n```bash\nmkdir -p $PROJECT_NAME && cd $PROJECT_NAME\nnpm init -y\nnpm install express uuid\nnpm install -D typescript @types\u002Fnode @types\u002Fexpress tsx\n```\n\n**Python:**\n\n```bash\nmkdir -p $PROJECT_NAME && cd $PROJECT_NAME\npython -m venv .venv && source .venv\u002Fbin\u002Factivate\npip install fastapi uvicorn uuid6\n```\n\n1.2. Create the JSON-RPC 2.0 request handler:\n\n```typescript\ninterface JsonRpcRequest {\n  jsonrpc: \"2.0\";\n  id: string | number;\n  method: string;\n  params?: Record\u003Cstring, unknown>;\n}\n\ninterface JsonRpcResponse {\n  jsonrpc: \"2.0\";\n  id: string | number;\n  result?: unknown;\n  error?: { code: number; message: string; data?: unknown };\n}\n\nfunction handleJsonRpc(request: JsonRpcRequest): JsonRpcResponse {\n  switch (request.method) {\n    case \"tasks\u002Fsend\":\n      return handleTaskSend(request);\n    case \"tasks\u002Fget\":\n      return handleTaskGet(request);\n    case \"tasks\u002Fcancel\":\n      return handleTaskCancel(request);\n    case \"tasks\u002FsendSubscribe\":\n      \u002F\u002F Handled separately via SSE\n      throw new Error(\"Use SSE endpoint for sendSubscribe\");\n    default:\n      return {\n        jsonrpc: \"2.0\",\n        id: request.id,\n        error: { code: -32601, message: `Method not found: ${request.method}` },\n      };\n  }\n}\n```\n\n1.3. Mount the JSON-RPC handler on a POST endpoint (typically `\u002F`):\n\n```typescript\napp.post(\"\u002F\", (req, res) => {\n  const response = handleJsonRpc(req.body);\n  res.json(response);\n});\n```\n\n1.4. Serve the Agent Card at `\u002F.well-known\u002Fagent.json`:\n\n```typescript\napp.get(\"\u002F.well-known\u002Fagent.json\", (req, res) => {\n  res.json(agentCard);\n});\n```\n\n**Got:** An HTTP server that accepts JSON-RPC 2.0 requests and serves the Agent Card.\n\n**If fail:** If JSON-RPC parsing fails, validate that the request body has `jsonrpc`, `method`, and `id` fields. Return `-32700` (Parse error) for malformed JSON and `-32600` (Invalid Request) for missing required fields.\n\n### Step 2: Implement Task State Machine\n\n2.1. Define the task model with all A2A lifecycle states:\n\n```typescript\ntype TaskState =\n  | \"submitted\"\n  | \"working\"\n  | \"input-required\"\n  | \"completed\"\n  | \"failed\"\n  | \"canceled\";\n\ninterface Task {\n  id: string;\n  sessionId: string;\n  status: {\n    state: TaskState;\n    message?: Message;\n    timestamp: string;\n  };\n  history?: TaskStatus[];\n  artifacts?: Artifact[];\n  metadata?: Record\u003Cstring, unknown>;\n}\n\ninterface Message {\n  role: \"user\" | \"agent\";\n  parts: Part[];\n}\n\ntype Part =\n  | { type: \"text\"; text: string }\n  | { type: \"file\"; file: { name: string; mimeType: string; bytes?: string; uri?: string } }\n  | { type: \"data\"; data: Record\u003Cstring, unknown> };\n```\n\n2.2. Implement state transition rules:\n\n```\nsubmitted  -> working | failed | canceled\nworking    -> completed | failed | canceled | input-required\ninput-required -> working | failed | canceled\ncompleted  -> (terminal)\nfailed     -> (terminal)\ncanceled   -> (terminal)\n```\n\n2.3. Create a task store with CRUD operations:\n\n```typescript\nclass TaskStore {\n  private tasks: Map\u003Cstring, Task> = new Map();\n\n  create(sessionId: string, message: Message): Task { ... }\n  get(taskId: string): Task | undefined { ... }\n  updateStatus(taskId: string, state: TaskState, message?: Message): Task { ... }\n  addArtifact(taskId: string, artifact: Artifact): void { ... }\n  cancel(taskId: string): Task { ... }\n}\n```\n\n2.4. If `stateTransitionHistory` is enabled in the Agent Card, append each status change to the task's `history` array with timestamps.\n\n**Got:** A task store that enforces valid state transitions and maintains history.\n\n**If fail:** If an invalid state transition is attempted (e.g., `completed` to `working`), return a JSON-RPC error with code `-32002` and a descriptive message. Never silently ignore invalid transitions.\n\n### Step 3: Add tasks\u002Fsend and tasks\u002Fget Methods\n\n3.1. Implement `tasks\u002Fsend` — the primary method for submitting tasks:\n\n```typescript\nfunction handleTaskSend(request: JsonRpcRequest): JsonRpcResponse {\n  const { id: taskId, sessionId, message } = request.params as TaskSendParams;\n\n  \u002F\u002F Create or resume task\n  let task = taskStore.get(taskId);\n  if (!task) {\n    task = taskStore.create(sessionId, message);\n  } else if (task.status.state === \"input-required\") {\n    taskStore.updateStatus(task.id, \"working\");\n  }\n\n  \u002F\u002F Route to skill handler based on message content\n  const skill = matchSkill(message);\n  if (!skill) {\n    taskStore.updateStatus(task.id, \"failed\", {\n      role: \"agent\",\n      parts: [{ type: \"text\", text: \"No matching skill for this request.\" }],\n    });\n    return { jsonrpc: \"2.0\", id: request.id, result: taskStore.get(task.id) };\n  }\n\n  \u002F\u002F Execute skill (async — task will transition to working, then completed\u002Ffailed)\n  executeSkill(skill, task, message).catch((error) => {\n    taskStore.updateStatus(task.id, \"failed\", {\n      role: \"agent\",\n      parts: [{ type: \"text\", text: error.message }],\n    });\n  });\n\n  return { jsonrpc: \"2.0\", id: request.id, result: taskStore.get(task.id) };\n}\n```\n\n3.2. Implement `tasks\u002Fget` — retrieve task status and artifacts:\n\n```typescript\nfunction handleTaskGet(request: JsonRpcRequest): JsonRpcResponse {\n  const { id: taskId, historyLength } = request.params as TaskGetParams;\n  const task = taskStore.get(taskId);\n\n  if (!task) {\n    return {\n      jsonrpc: \"2.0\",\n      id: request.id,\n      error: { code: -32001, message: `Task not found: ${taskId}` },\n    };\n  }\n\n  \u002F\u002F Optionally trim history to requested length\n  const result = historyLength !== undefined\n    ? { ...task, history: task.history?.slice(-historyLength) }\n    : task;\n\n  return { jsonrpc: \"2.0\", id: request.id, result };\n}\n```\n\n3.3. Implement `tasks\u002Fcancel`:\n\n```typescript\nfunction handleTaskCancel(request: JsonRpcRequest): JsonRpcResponse {\n  const { id: taskId } = request.params as TaskCancelParams;\n  try {\n    const task = taskStore.cancel(taskId);\n    return { jsonrpc: \"2.0\", id: request.id, result: task };\n  } catch (error) {\n    return {\n      jsonrpc: \"2.0\",\n      id: request.id,\n      error: { code: -32002, message: (error as Error).message },\n    };\n  }\n}\n```\n\n**Got:** Working `tasks\u002Fsend`, `tasks\u002Fget`, and `tasks\u002Fcancel` methods that correctly manage task lifecycle.\n\n**If fail:** If skill matching fails, return the task in `failed` state with a descriptive message. If the task store is full, return `-32003` (resource exhausted).\n\n### Step 4: Implement SSE Streaming for tasks\u002FsendSubscribe\n\n4.1. Create an SSE endpoint for streaming task updates:\n\n```typescript\napp.post(\"\u002Fsubscribe\", (req, res) => {\n  const request = req.body as JsonRpcRequest;\n  if (request.method !== \"tasks\u002FsendSubscribe\") {\n    res.status(400).json({ error: \"Only tasks\u002FsendSubscribe supported\" });\n    return;\n  }\n\n  \u002F\u002F Set SSE headers\n  res.setHeader(\"Content-Type\", \"text\u002Fevent-stream\");\n  res.setHeader(\"Cache-Control\", \"no-cache\");\n  res.setHeader(\"Connection\", \"keep-alive\");\n\n  const { id: taskId, sessionId, message } = request.params as TaskSendParams;\n  let task = taskStore.get(taskId) ?? taskStore.create(sessionId, message);\n\n  \u002F\u002F Send initial status\n  sendSSEEvent(res, \"status\", {\n    id: request.id,\n    result: { id: task.id, status: task.status },\n  });\n\n  \u002F\u002F Subscribe to task updates\n  const unsubscribe = taskStore.onUpdate(task.id, (updatedTask) => {\n    if (updatedTask.status.state === \"working\") {\n      sendSSEEvent(res, \"status\", {\n        id: request.id,\n        result: { id: updatedTask.id, status: updatedTask.status },\n      });\n    }\n\n    if (updatedTask.artifacts?.length) {\n      sendSSEEvent(res, \"artifact\", {\n        id: request.id,\n        result: { id: updatedTask.id, artifact: updatedTask.artifacts.at(-1) },\n      });\n    }\n\n    \u002F\u002F Close stream on terminal states\n    if ([\"completed\", \"failed\", \"canceled\"].includes(updatedTask.status.state)) {\n      sendSSEEvent(res, \"status\", {\n        id: request.id,\n        result: { id: updatedTask.id, status: updatedTask.status, final: true },\n      });\n      unsubscribe();\n      res.end();\n    }\n  });\n\n  \u002F\u002F Handle client disconnect\n  req.on(\"close\", () => {\n    unsubscribe();\n  });\n});\n\nfunction sendSSEEvent(res: Response, event: string, data: unknown): void {\n  res.write(`event: ${event}\\ndata: ${JSON.stringify(data)}\\n\\n`);\n}\n```\n\n4.2. Add an event emitter or pub\u002Fsub mechanism to the task store:\n\n```typescript\nclass TaskStore {\n  private listeners: Map\u003Cstring, Set\u003C(task: Task) => void>> = new Map();\n\n  onUpdate(taskId: string, callback: (task: Task) => void): () => void {\n    if (!this.listeners.has(taskId)) {\n      this.listeners.set(taskId, new Set());\n    }\n    this.listeners.get(taskId)!.add(callback);\n    return () => this.listeners.get(taskId)?.delete(callback);\n  }\n\n  private notifyListeners(taskId: string): void {\n    const task = this.get(taskId);\n    if (task) {\n      this.listeners.get(taskId)?.forEach((cb) => cb(task));\n    }\n  }\n}\n```\n\n4.3. Emit events from all task state transitions and artifact additions.\n\n**Got:** SSE streaming that sends real-time status and artifact events as the task progresses.\n\n**If fail:** If SSE connection drops, the client should be able to reconnect and use `tasks\u002Fget` to retrieve the current state. Ensure the task store does not depend on active SSE connections.\n\n### Step 5: Add Push Notification Webhook Support\n\n5.1. If `pushNotifications` is enabled in the Agent Card, implement webhook registration via `tasks\u002FpushNotification\u002Fset`:\n   - Accept a `PushNotificationConfig` with `url` (HTTPS required), optional `token`, and `events` array (`[\"status\", \"artifact\"]`)\n   - Validate the webhook URL uses HTTPS; reject with error code `-32004` otherwise\n   - Store the config in the task store, keyed by task ID\n\n5.2. Send webhook callbacks on task state changes:\n   - On each state transition or artifact addition, check for a registered push config\n   - POST a JSON payload with `taskId`, `eventType`, `status`, and `timestamp` to the webhook URL\n   - Include `Authorization: Bearer \u003Ctoken>` header if a token was provided\n\n5.3. Implement retry logic for failed webhooks (exponential backoff, max 3 retries).\n\n5.4. Add `tasks\u002FpushNotification\u002Fget` to retrieve the current push config for a task.\n\n**Got:** Webhook registration and delivery with retry logic.\n\n**If fail:** Push notification failures must never affect task execution. Log errors and continue. If the webhook URL is persistently unreachable, remove the subscription after max retries.\n\n### Step 6: Integrate with Agent Card for Discovery\n\n6.1. Load and serve the Agent Card at startup:\n   - Parse `agent-card.json` and validate capabilities match implementation\n   - Throw at startup if the card advertises `streaming: true` but SSE is not enabled\n   - Throw at startup if the card advertises `pushNotifications: true` but webhooks are not enabled\n\n6.2. Add CORS headers for cross-origin Agent Card discovery:\n   - Set `Access-Control-Allow-Origin: *` on `\u002F.well-known\u002Fagent.json`\n   - Allow `GET` and `OPTIONS` methods\n\n6.3. Add authentication middleware matching the Agent Card's scheme:\n   - Skip authentication for `\u002F.well-known\u002Fagent.json` (Agent Card is always public)\n   - For all other endpoints, validate the `Authorization` header or API key\n   - Return HTTP 401 with JSON-RPC error code `-32000` for unauthorized requests\n\n6.4. Start the server and verify end-to-end:\n\n```bash\n# Start server\nnpm run dev\n\n# Fetch Agent Card\ncurl -s http:\u002F\u002Flocalhost:3000\u002F.well-known\u002Fagent.json | python3 -m json.tool\n\n# Send a task\ncurl -X POST http:\u002F\u002Flocalhost:3000\u002F \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tasks\u002Fsend\",\"params\":{\"id\":\"task-1\",\"sessionId\":\"session-1\",\"message\":{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"text\":\"Analyze my dataset\"}]}}}'\n```\n\n**Got:** A running A2A server that serves its Agent Card, accepts tasks, and manages their full lifecycle.\n\n**If fail:** If the Agent Card capabilities do not match the implementation, the startup validation from 6.1 will catch the mismatch. Fix the implementation or update the Agent Card to match.\n\n## Validation\n\n- [ ] Server starts and serves Agent Card at `\u002F.well-known\u002Fagent.json`\n- [ ] `tasks\u002Fsend` creates tasks and transitions them through the lifecycle\n- [ ] `tasks\u002Fget` retrieves task status and artifacts\n- [ ] `tasks\u002Fcancel` moves tasks to the canceled state\n- [ ] SSE streaming sends real-time status and artifact events (if enabled)\n- [ ] Push notifications deliver webhooks on state changes (if enabled)\n- [ ] Invalid state transitions return appropriate JSON-RPC errors\n- [ ] Authentication rejects unauthorized requests (if configured)\n- [ ] Agent Card capabilities accurately reflect server implementation\n- [ ] All JSON-RPC responses include `jsonrpc: \"2.0\"` and correct `id`\n\n## Pitfalls\n\n- **Missing JSON-RPC error codes**: The A2A protocol defines specific error codes. Use `-32700` (parse error), `-32600` (invalid request), `-32601` (method not found), and custom codes for domain errors.\n- **Task ID collisions**: Use UUIDs for task IDs. If the client provides an ID, validate uniqueness before creating the task.\n- **SSE connection leaks**: Clean up SSE subscriptions when the client disconnects. Use `req.on(\"close\")` to detect disconnects.\n- **Blocking skill execution**: Long-running skills must execute asynchronously. Return the task in `submitted` or `working` state immediately, then update via events.\n- **Agent Card drift**: If the server implementation changes but the Agent Card is not updated, clients will have incorrect expectations. Validate at startup.\n- **Ignoring terminal states**: Once a task reaches `completed`, `failed`, or `canceled`, no further state transitions are allowed. Guard against this in the state machine.\n\n## Related Skills\n\n- `design-a2a-agent-card` - design the Agent Card this server implements\n- `test-a2a-interop` - validate the server against A2A conformance tests\n- `build-custom-mcp-server` - MCP server patterns that inform A2A implementation\n- `scaffold-mcp-server` - scaffolding patterns applicable to A2A server setup\n- `configure-ingress-networking` - production deployment with TLS and routing\n",{"name":5,"locale":23,"license":14,"metadata":24,"translator":31,"description":32,"allowed-tools":33,"source_commit":34,"source_locale":35,"translation_date":36},"caveman-lite",{"tags":25,"author":26,"domain":27,"version":28,"language":29,"complexity":30},"a2a, server, json-rpc, task-lifecycle, streaming, sse","Philipp Thoss","a2a-protocol","1.0","multi","advanced","Julius Brussee homage — caveman","Implement a JSON-RPC 2.0 A2A server with full task lifecycle management (submitted\u002Fworking\u002Fcompleted\u002Ffailed\u002Fcanceled\u002Finput-required), SSE streaming, and push notifications. Use when implementing an agent that participates in multi-agent A2A workflows, building a backend for an Agent Card, adding A2A protocol support to an existing agent or service, or deploying an agent that must interoperate with other A2A-compliant agents.\n","Read Write Edit Bash Grep Glob WebFetch","82c77053","en","2026-04-24","master","f483e54f3ad5f202a77d45f2e57f8d970b71195f","skills_library\u002Fimplement-a2a-server",2,"https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills","https:\u002F\u002Fgithub.com\u002Froohe","yoou.link","2026-05-19 15:56:07",{"source":8,"skillName":5,"commands":46,"prompt":56,"zipAvailable":57},[47,50,53],{"tool":48,"command":49},"npx","npx skills add roohe\u002Fagentic-super-skills --skill implement-a2a-server",{"tool":51,"command":52},"bunx","bunx skills add roohe\u002Fagentic-super-skills --skill implement-a2a-server",{"tool":54,"command":55},"pnpm","pnpm dlx skills add roohe\u002Fagentic-super-skills --skill implement-a2a-server","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fimplement-a2a-server\u002FSKILL.md",true,[],[60,67,74,81,88,95],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":18},"01M73D865CZME2FCMKA4PQM348","zarr-python","Chunked N-D arrays for cloud storage. Compressed arrays, parallel I\u002FO, S3\u002FGCS integration, NumPy\u002FDask\u002FXarray compatible, for large-scale scientific computing pipelines.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fzarr-python\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M73D7Z64J4ABWZJD7P44XBBF","youtube-downloader","Download and process YouTube content for research. Use when: downloading competitor videos for analysis; extracting audio for podcasts; getting transcripts for content repurposing; archiving webinars; research content curation","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fyoutube-downloader\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":18},"01M73D7K8778TGZV3GJFR3703D","yc-pitch-deck","Create a compelling startup pitch deck that follows the structure proven to raise billions from top investors. Master the YC and Sequoia formats that get founders funded. Use when: **Fundraising** to create investor pitch decks; **YC application** to structure your narrative; **Demo Day prep** to craft your 2-minute pitch; **Angel investors** to communicate your opportunity; **Partnership pitches** to structure compelling asks","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fyc-pitch-deck\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":18},"01M73D70KJSE0E8Z28YMNNRT04","x-twitter-scraper","Use when the user needs X (Twitter) data or confirmation-gated X actions through Xquik: tweet search, user lookup, follower extraction, media download, monitoring, webhooks, MCP, SDKs, posting, likes, DMs, and profile updates. Requires a Xquik API key. Never ask for X login material.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fx-twitter-scraper\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":18},"01M73D6ED01GV077R7K4NZNFZJ","write-vignette","Create R package vignettes using R Markdown or Quarto. Covers vignette setup, YAML configuration, code chunk options, building and testing, and CRAN requirements for vignettes. Use when adding a Getting Started tutorial, documenting complex workflows spanning multiple functions, creating domain-specific guides, or when CRAN submission requires user-facing documentation beyond function help pages.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fwrite-vignette\u002FSKILL.md",[],[],{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":18},"01M73D69YJR0BK3NFHE0CYG3EF","write-validation-documentation","Write IQ\u002FOQ\u002FPQ validation documentation for computerized systems in regulated environments. Covers protocols, reports, test scripts, deviation handling, and approval workflows. Use when validating R or other software for regulated use, preparing for a regulatory audit, documenting qualification of computing environments, or creating and updating validation protocols and reports for new or re-qualified systems.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fwrite-validation-documentation\u002FSKILL.md",[],[]]