From 723e0f36a40f6a132b72e96e134c1f59765aa637 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 22:35:52 -0800 Subject: [PATCH 01/17] feat(learning): read learnings as agents see them Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25291e01-0146-42cb-ac6d-f5e1dd5c35f5 --- packages/learning/README.md | 4 ++-- packages/learning/mcp.d.mts | 2 ++ packages/learning/src/cli.mjs | 9 +++++++-- packages/learning/src/mcp.mjs | 3 +++ packages/learning/test/cli.test.mjs | 21 +++++++++++++++++++++ 5 files changed, 35 insertions(+), 4 deletions(-) diff --git a/packages/learning/README.md b/packages/learning/README.md index 88dd0550..c9e7d977 100644 --- a/packages/learning/README.md +++ b/packages/learning/README.md @@ -136,7 +136,7 @@ The agent gets these tools: The server tells the agent when to call each tool. Errors that aren't learning refusals reach the agent as a generic message, and their cause is written to the server's standard error. Copilot CLI passes a server's instructions to the model only when the server is allowlisted or you start it with `--allow-all-mcp-server-instructions`, so the tool descriptions repeat what matters. The agent acts as `--actor`, `agent:mcp` by default. It can never accept, reject, edit, or delete a learning. -Hosts such as Hub can serve the same tools by importing `createLearningMcpServer` from `@github/replica-learning/mcp` and passing their own backend. The tools and their wording then stay the same everywhere. +Hosts such as Hub can serve the same tools by importing `createLearningMcpServer` from `@github/replica-learning/mcp` and passing their own backend. The tools and their wording then stay the same everywhere. The module also exports `LearningError`; throw it from the backend to give the agent a code and message. ## Rules @@ -160,7 +160,7 @@ Hosts such as Hub can serve the same tools by importing `createLearningMcpServer - Damaged records stop the operations that read them. If a grant, withdrawal, episode, event, or collection that an operation reads fails its schema, digest, or scope check, that operation refuses to run until `verify` finds the damage and someone repairs it. Learning decisions read only the records tied to their evidence, so damage elsewhere in the store does not block them. `verify` still checks every record. A damaged learning is never used, and reading it shows only its ID, state, kind, theme, and digests, each strictly checked. These checks catch altered records; they cannot catch a provider that omits or replays whole records. - Comment text is data. It never changes settings or decisions, terminal output quotes it, and recall never includes raw comments. Input JSON that repeats a member name is refused. - Recall writes each learning as plain lines of data, with the learning's text quoted as a JSON string. Every field, including who accepted the learning, has its line breaks turned into spaces and its control characters and invisible formatting characters removed: zero-width characters, tag characters, and marks that reorder text. The store refuses a person or agent ID that contains such characters, and the v1 schemas refuse a record with such an actor ID, so an ID reads the same everywhere it is shown. The character budget includes the full heading, framing, quotes, and newlines. A budget too small for the required framing is refused with the minimum it needs; recall never cuts off the framing or returns oversized text. -- Reading a learning is a use. `show` and `memories` read for review; when a learning's evidence no longer permits review, they withhold its content, evidence, and rationale. `show --history` checks each version on its own, so an older version whose evidence or counterevidence no longer permits review shows only its state and digests. +- Reading a learning is a use. `show` and `memories` read for review; when a learning's evidence no longer permits review, they withhold its content, evidence, and rationale. Add `--purpose instruction` to see exactly what an agent may read. `show --history` checks each version on its own, so an older version whose evidence or counterevidence no longer permits review shows only its state and digests. ## Contracts diff --git a/packages/learning/mcp.d.mts b/packages/learning/mcp.d.mts index 09d93107..574ea1f4 100644 --- a/packages/learning/mcp.d.mts +++ b/packages/learning/mcp.d.mts @@ -1,6 +1,8 @@ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js" import type { MemoryReading } from "./index.mjs" +export { LearningError } from "./index.mjs" + /** * What a host supplies to serve the learning tools. Each method receives the tool's * checked input and returns the JSON the agent sees. Throw a LearningError to give the diff --git a/packages/learning/src/cli.mjs b/packages/learning/src/cli.mjs index ebd4ecbb..6ba47450 100644 --- a/packages/learning/src/cli.mjs +++ b/packages/learning/src/cli.mjs @@ -40,8 +40,11 @@ Inspect observations [--purpose

] [--event ]... Evidence a purpose may use now; select up to 100 event IDs and only their containing episodes - memories [--state ]... Learnings with their state and whether they are recalled - show [--history] One learning, its evidence, and its digests + memories [--state ]... [--purpose

] + Learnings with their state and whether they are + recalled; --purpose instruction shows what agents see + show [--history] [--purpose

] + One learning, its evidence, and its digests operation-status --operation-id Whether one host decision operation is in intact history verify Re-check every record's schema, digest, and history @@ -1029,6 +1032,7 @@ async function memories(session) { const { store } = await open(session) const items = await store.queryMemory(context(session, actor(session)), { states: session.values.state, + purpose: single(session.values.purpose, "--purpose") ?? "review", }) session.out( items, @@ -1051,6 +1055,7 @@ async function show(session) { const { store } = await open(session) const item = await store.getMemory(context(session, actor(session)), id, { history: Boolean(session.values.history), + purpose: single(session.values.purpose, "--purpose") ?? "review", }) const { record, status } = item const head = [ diff --git a/packages/learning/src/mcp.mjs b/packages/learning/src/mcp.mjs index 033417e6..0e570ea9 100644 --- a/packages/learning/src/mcp.mjs +++ b/packages/learning/src/mcp.mjs @@ -2,6 +2,9 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js" import { z } from "zod" import { LearningError } from "./errors.mjs" +// Agents see a code and message only for this exact class, so hosts need it too. +export { LearningError } + const INSTRUCTIONS = `This server holds the learnings a team accepted from past reviews of its prototypes. Before you start a task, call get_guidance with a short description of the task and follow the learnings it returns. Keep its guidanceId and each learning's deliveryId. diff --git a/packages/learning/test/cli.test.mjs b/packages/learning/test/cli.test.mjs index 3d0df224..68885d2c 100644 --- a/packages/learning/test/cli.test.mjs +++ b/packages/learning/test/cli.test.mjs @@ -1163,6 +1163,27 @@ describe("replica-learning CLI: guard rails", () => { assert.match(refused.stderr, /invalid_input.*budget must be at least/) }) + it("shows people a learning that agents can no longer read", async () => { + const repo = checkout("purpose-reading") + const { grant, proposal } = await learnFromReviews(repo) + await ok(repo, [ + "grants", + "withdraw", + grant.id, + "--purpose", + "instruction", + "--by", + "github:ana-designer", + ]) + + const forPeople = (await ok(repo, ["memories", "--json"])).json() + assert.equal(forPeople[0].withheld, false) + const forAgents = (await ok(repo, ["memories", "--purpose", "instruction", "--json"])).json() + assert.equal(forAgents[0].withheld, true) + const shown = await ok(repo, ["show", proposal.id, "--purpose", "instruction"]) + assert.match(shown.stdout, /Content, evidence, and rationale are withheld/) + }) + it("rejects usage errors with exit code 2", async () => { const repo = checkout("usage") assert.equal((await cli(repo, [])).code, 2) From d52b12705659ba6a640cb6999acd3085d9bc907b Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 22:35:56 -0800 Subject: [PATCH 02/17] chore(hub): add the MCP SDK Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25291e01-0146-42cb-ac6d-f5e1dd5c35f5 --- hub/package-lock.json | 187 ++++++++++++++++++++++++++++++++++++++++++ hub/package.json | 1 + 2 files changed, 188 insertions(+) diff --git a/hub/package-lock.json b/hub/package-lock.json index 0e36e748..790336da 100644 --- a/hub/package-lock.json +++ b/hub/package-lock.json @@ -11,6 +11,7 @@ "dependencies": { "@azure/identity": "4.13.0", "@azure/storage-blob": "12.33.0", + "@modelcontextprotocol/sdk": "1.32.2", "@opentelemetry/api": "1.10.0", "@opentelemetry/context-async-hooks": "3.0.0", "@opentelemetry/exporter-trace-otlp-proto": "0.300.0", @@ -1545,6 +1546,18 @@ "url": "https://github.com/sponsors/colinhacks" } }, + "node_modules/@hono/node-server": { + "version": "2.1.9", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@hono/node-server/-/node-server-2.1.9.tgz", + "integrity": "sha512-Sk4NQd3GFY0WZWCzndwFMPwJhtD0y9qjsQ+pjID0/03nK9pxyBCUoUHCho8QYBLBVhi0ssL8UkNPHqbgSOFPIQ==", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "hono": "^4 || ^5.0.0-0" + } + }, "node_modules/@humanfs/core": { "version": "0.19.2", "dev": true, @@ -2035,6 +2048,55 @@ "react": ">=16" } }, + "node_modules/@modelcontextprotocol/sdk": { + "version": "1.32.2", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/@modelcontextprotocol/sdk/-/sdk-1.32.2.tgz", + "integrity": "sha512-SWsVtH/0vULSQStoZ6xxH2K09Li8fXYTMC64ZeogCdpZ3XSi1eCPOByV1OpuJxuI3OcmHhosDWYyii07tpPsLw==", + "license": "MIT", + "dependencies": { + "@hono/node-server": "^1.19.9 || ^2.0.5", + "ajv": "^8.17.1", + "ajv-formats": "^3.0.1", + "content-type": "^1.0.5", + "cors": "^2.8.5", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.0", + "express": "^5.2.1", + "express-rate-limit": "^8.2.1", + "hono": "^4.11.4", + "jose": "^6.1.3", + "json-schema-typed": "^8.0.2", + "pkce-challenge": "^5.0.0", + "raw-body": "^3.0.0", + "zod": "^3.25 || ^4.0", + "zod-to-json-schema": "^3.25.1" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@cfworker/json-schema": "^4.1.1", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "@cfworker/json-schema": { + "optional": true + }, + "zod": { + "optional": false + } + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/@msgpackr-extract/msgpackr-extract-darwin-arm64": { "version": "3.0.4", "resolved": "https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@msgpackr-extract/msgpackr-extract-darwin-arm64/-/msgpackr-extract-darwin-arm64-3.0.4.tgz", @@ -5241,6 +5303,23 @@ "url": "https://github.com/sponsors/epoberezkin" } }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha1-PV3HYryhdnnDwup+kK1rdTIwlXg=", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, "node_modules/ansi-regex": { "version": "5.0.1", "dev": true, @@ -5679,6 +5758,23 @@ "node": ">=6.6.0" } }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/cron-parser": { "version": "5.10.2", "license": "MIT", @@ -6405,6 +6501,27 @@ "node": ">=0.8.x" } }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "license": "MIT", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.1.1", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/eventsource-parser/-/eventsource-parser-3.1.1.tgz", + "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/exit-hook": { "version": "5.1.0", "dev": true, @@ -6465,6 +6582,25 @@ "url": "https://opencollective.com/express" } }, + "node_modules/express-rate-limit": { + "version": "8.7.5", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/express-rate-limit/-/express-rate-limit-8.7.5.tgz", + "integrity": "sha512-wi+v38cx2EqD0JnhE/e74o5tFqKWUOAPFJIgyEiqJ8v2MNpoOAA3kI2hXYOI+YM+HE5yqbdAlVxm2GqOIeYOgA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "ip-address": "^10.2.0" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, "node_modules/exsolve": { "version": "1.1.3", "license": "MIT" @@ -6871,6 +7007,15 @@ "hermes-estree": "0.25.1" } }, + "node_modules/hono": { + "version": "4.13.19", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/hono/-/hono-4.13.19.tgz", + "integrity": "sha512-KmXvQAXwcAHV+muzbIwoJ23niEB5nMoDVr9WcRkU8mvjUECm/1+7v4Jgp7P7a+H6MLFrh+vXrGonGrGS+RQfkA==", + "license": "MIT", + "engines": { + "node": ">=16.9.0" + } + }, "node_modules/hookified": { "version": "1.15.1", "dev": true, @@ -6980,6 +7125,15 @@ "node": ">=12" } }, + "node_modules/ip-address": { + "version": "10.7.6", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/ip-address/-/ip-address-10.7.6.tgz", + "integrity": "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, "node_modules/ipaddr.js": { "version": "1.9.1", "license": "MIT", @@ -7180,6 +7334,12 @@ "version": "1.0.0", "license": "MIT" }, + "node_modules/json-schema-typed": { + "version": "8.0.2", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/json-schema-typed/-/json-schema-typed-8.0.2.tgz", + "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", + "license": "BSD-2-Clause" + }, "node_modules/json-stable-stringify-without-jsonify": { "version": "1.0.1", "dev": true, @@ -7911,6 +8071,15 @@ "node": ">=18" } }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/object-inspect": { "version": "1.13.4", "license": "MIT", @@ -8334,6 +8503,15 @@ "version": "7.1.0", "license": "MIT" }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/pkce-challenge/-/pkce-challenge-5.0.1.tgz", + "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", + "license": "MIT", + "engines": { + "node": ">=16.20.0" + } + }, "node_modules/pkg-types": { "version": "2.3.3", "license": "MIT", @@ -9924,6 +10102,15 @@ "url": "https://github.com/sponsors/colinhacks" } }, + "node_modules/zod-to-json-schema": { + "version": "3.25.2", + "resolved": "https://pkgs.dev.azure.com/github-cfs/GitHubCFS/_packaging/github-cfs-oss/npm/registry/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz", + "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==", + "license": "ISC", + "peerDependencies": { + "zod": "^3.25.28 || ^4" + } + }, "node_modules/zod-validation-error": { "version": "4.0.2", "dev": true, diff --git a/hub/package.json b/hub/package.json index f5dbddc3..8a11e9c9 100644 --- a/hub/package.json +++ b/hub/package.json @@ -71,6 +71,7 @@ "dependencies": { "@azure/identity": "4.13.0", "@azure/storage-blob": "12.33.0", + "@modelcontextprotocol/sdk": "1.32.2", "@opentelemetry/api": "1.10.0", "@opentelemetry/context-async-hooks": "3.0.0", "@opentelemetry/exporter-trace-otlp-proto": "0.300.0", From 9a4177a3dcfdb95551913c7048cf41fa7e8a3165 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 22:57:16 -0800 Subject: [PATCH 03/17] feat(hub): store agent clients, approvals, and connections Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25291e01-0146-42cb-ac6d-f5e1dd5c35f5 --- .../index.test.tsx | 0 .../index.tsx | 0 .../stories.tsx | 0 .../styles.css | 0 .../types.ts | 0 hub/schema/agent-authorization.prisma | 24 +++++ hub/schema/agent-client.prisma | 17 ++++ hub/schema/agent-connection.prisma | 32 +++++++ .../authentication-provider-revision.prisma | 1 + hub/schema/external-identity.prisma | 1 + hub/schema/hub-session.prisma | 1 + hub/schema/membership.prisma | 1 + .../migration.sql | 92 +++++++++++++++++++ 13 files changed, 169 insertions(+) rename hub/client/pages/{agent-connections-prototype => agent-connections-page}/index.test.tsx (100%) rename hub/client/pages/{agent-connections-prototype => agent-connections-page}/index.tsx (100%) rename hub/client/pages/{agent-connections-prototype => agent-connections-page}/stories.tsx (100%) rename hub/client/pages/{agent-connections-prototype => agent-connections-page}/styles.css (100%) rename hub/client/pages/{agent-connections-prototype => agent-connections-page}/types.ts (100%) create mode 100644 hub/schema/agent-authorization.prisma create mode 100644 hub/schema/agent-client.prisma create mode 100644 hub/schema/agent-connection.prisma create mode 100644 hub/schema/migrations/20261223170000_agent_connections/migration.sql diff --git a/hub/client/pages/agent-connections-prototype/index.test.tsx b/hub/client/pages/agent-connections-page/index.test.tsx similarity index 100% rename from hub/client/pages/agent-connections-prototype/index.test.tsx rename to hub/client/pages/agent-connections-page/index.test.tsx diff --git a/hub/client/pages/agent-connections-prototype/index.tsx b/hub/client/pages/agent-connections-page/index.tsx similarity index 100% rename from hub/client/pages/agent-connections-prototype/index.tsx rename to hub/client/pages/agent-connections-page/index.tsx diff --git a/hub/client/pages/agent-connections-prototype/stories.tsx b/hub/client/pages/agent-connections-page/stories.tsx similarity index 100% rename from hub/client/pages/agent-connections-prototype/stories.tsx rename to hub/client/pages/agent-connections-page/stories.tsx diff --git a/hub/client/pages/agent-connections-prototype/styles.css b/hub/client/pages/agent-connections-page/styles.css similarity index 100% rename from hub/client/pages/agent-connections-prototype/styles.css rename to hub/client/pages/agent-connections-page/styles.css diff --git a/hub/client/pages/agent-connections-prototype/types.ts b/hub/client/pages/agent-connections-page/types.ts similarity index 100% rename from hub/client/pages/agent-connections-prototype/types.ts rename to hub/client/pages/agent-connections-page/types.ts diff --git a/hub/schema/agent-authorization.prisma b/hub/schema/agent-authorization.prisma new file mode 100644 index 00000000..26aa0f13 --- /dev/null +++ b/hub/schema/agent-authorization.prisma @@ -0,0 +1,24 @@ +model AgentAuthorization { + // ID columns + id String @id @default(uuid()) @db.Uuid + clientId String @map("client_id") @db.Uuid + sessionId String? @map("session_id") @db.Uuid + + // Relations + client AgentClient @relation(fields: [clientId], references: [id], onDelete: Cascade) + session HubSession? @relation(fields: [sessionId], references: [id], onDelete: SetNull) + + // Attribute columns + redirectUri String @map("redirect_uri") @db.VarChar(2048) + codeChallenge String @map("code_challenge") @db.VarChar(128) + state String? @db.VarChar(1024) + codeDigest String? @unique @map("code_digest") @db.VarChar(64) + expiresAt DateTime @map("expires_at") @db.Timestamptz(3) + approvedAt DateTime? @map("approved_at") @db.Timestamptz(3) + consumedAt DateTime? @map("consumed_at") @db.Timestamptz(3) + + @@index([clientId]) + @@index([sessionId]) + @@index([expiresAt]) + @@map("agent_authorizations") +} diff --git a/hub/schema/agent-client.prisma b/hub/schema/agent-client.prisma new file mode 100644 index 00000000..06b3164a --- /dev/null +++ b/hub/schema/agent-client.prisma @@ -0,0 +1,17 @@ +model AgentClient { + // ID columns + id String @id @default(uuid()) @db.Uuid + + // Relations + authorizations AgentAuthorization[] + connections AgentConnection[] + + // Attribute columns + name String @db.VarChar(200) + redirectUris String[] @map("redirect_uris") + + // Timestamp columns + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + + @@map("agent_clients") +} diff --git a/hub/schema/agent-connection.prisma b/hub/schema/agent-connection.prisma new file mode 100644 index 00000000..7a40fbde --- /dev/null +++ b/hub/schema/agent-connection.prisma @@ -0,0 +1,32 @@ +model AgentConnection { + // ID columns + id String @id @default(uuid()) @db.Uuid + clientId String @map("client_id") @db.Uuid + membershipId String @map("membership_id") @db.Uuid + externalIdentityId String @map("external_identity_id") @db.Uuid + providerRevisionId String @map("provider_revision_id") @db.Uuid + + // Relations + client AgentClient @relation(fields: [clientId], references: [id], onDelete: Cascade) + membership Membership @relation(fields: [membershipId], references: [id], onDelete: Cascade) + externalIdentity ExternalIdentity @relation(fields: [externalIdentityId], references: [id], onDelete: Cascade) + providerRevision AuthenticationProviderRevision @relation(fields: [providerRevisionId], references: [id], onDelete: Cascade) + + // Attribute columns + revocationRevision Int @map("revocation_revision") + tokenDigest String @unique @map("token_digest") @db.VarChar(64) + refreshDigest String @unique @map("refresh_digest") @db.VarChar(64) + expiresAt DateTime @map("expires_at") @db.Timestamptz(3) + inactiveAt DateTime @map("inactive_at") @db.Timestamptz(3) + lastUsedAt DateTime? @map("last_used_at") @db.Timestamptz(3) + revokedAt DateTime? @map("revoked_at") @db.Timestamptz(3) + + // Timestamp columns + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + + @@index([clientId]) + @@index([externalIdentityId]) + @@index([providerRevisionId]) + @@index([membershipId, externalIdentityId, createdAt]) + @@map("agent_connections") +} diff --git a/hub/schema/authentication-provider-revision.prisma b/hub/schema/authentication-provider-revision.prisma index 74d96f41..1069a40f 100644 --- a/hub/schema/authentication-provider-revision.prisma +++ b/hub/schema/authentication-provider-revision.prisma @@ -11,6 +11,7 @@ model AuthenticationProviderRevision { hubSessions HubSession[] membershipAssignments MembershipAssignment[] canvasGrants CanvasGrant[] + agentConnections AgentConnection[] // Attribute columns revision Int diff --git a/hub/schema/external-identity.prisma b/hub/schema/external-identity.prisma index 510cfe1e..125afdb6 100644 --- a/hub/schema/external-identity.prisma +++ b/hub/schema/external-identity.prisma @@ -10,6 +10,7 @@ model ExternalIdentity { hubSessions HubSession[] sensitiveAuthorizations SensitiveAuthorization[] canvasGrants CanvasGrant[] + agentConnections AgentConnection[] shareLinks ShareLink[] // Attribute columns diff --git a/hub/schema/hub-session.prisma b/hub/schema/hub-session.prisma index 9037094c..1e385f80 100644 --- a/hub/schema/hub-session.prisma +++ b/hub/schema/hub-session.prisma @@ -11,6 +11,7 @@ model HubSession { providerRevision AuthenticationProviderRevision? @relation(fields: [providerRevisionId], references: [id], onDelete: Restrict) sensitiveAuthorizations SensitiveAuthorization[] canvasPairings CanvasPairing[] + agentAuthorizations AgentAuthorization[] analyticsDestinationAuthorization AnalyticsDestinationAuthorization? // Attribute columns diff --git a/hub/schema/membership.prisma b/hub/schema/membership.prisma index eef1d106..58d61141 100644 --- a/hub/schema/membership.prisma +++ b/hub/schema/membership.prisma @@ -19,6 +19,7 @@ model Membership { sharedLearnings LearningShare[] @relation("LearningShareSharedBy") withdrawnLearningShares LearningShare[] @relation("LearningShareWithdrawnBy") canvasGrants CanvasGrant[] + agentConnections AgentConnection[] // Attribute columns lifecycle MembershipLifecycle @default(ACTIVE) diff --git a/hub/schema/migrations/20261223170000_agent_connections/migration.sql b/hub/schema/migrations/20261223170000_agent_connections/migration.sql new file mode 100644 index 00000000..e74b176c --- /dev/null +++ b/hub/schema/migrations/20261223170000_agent_connections/migration.sql @@ -0,0 +1,92 @@ +-- CreateTable +CREATE TABLE "agent_authorizations" ( + "id" UUID NOT NULL, + "client_id" UUID NOT NULL, + "session_id" UUID, + "redirect_uri" VARCHAR(2048) NOT NULL, + "code_challenge" VARCHAR(128) NOT NULL, + "state" VARCHAR(1024), + "code_digest" VARCHAR(64), + "expires_at" TIMESTAMPTZ(3) NOT NULL, + "approved_at" TIMESTAMPTZ(3), + "consumed_at" TIMESTAMPTZ(3), + + CONSTRAINT "agent_authorizations_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "agent_clients" ( + "id" UUID NOT NULL, + "name" VARCHAR(200) NOT NULL, + "redirect_uris" TEXT[], + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "agent_clients_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "agent_connections" ( + "id" UUID NOT NULL, + "client_id" UUID NOT NULL, + "membership_id" UUID NOT NULL, + "external_identity_id" UUID NOT NULL, + "provider_revision_id" UUID NOT NULL, + "revocation_revision" INTEGER NOT NULL, + "token_digest" VARCHAR(64) NOT NULL, + "refresh_digest" VARCHAR(64) NOT NULL, + "expires_at" TIMESTAMPTZ(3) NOT NULL, + "inactive_at" TIMESTAMPTZ(3) NOT NULL, + "last_used_at" TIMESTAMPTZ(3), + "revoked_at" TIMESTAMPTZ(3), + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "agent_connections_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "agent_authorizations_code_digest_key" ON "agent_authorizations"("code_digest"); + +-- CreateIndex +CREATE INDEX "agent_authorizations_client_id_idx" ON "agent_authorizations"("client_id"); + +-- CreateIndex +CREATE INDEX "agent_authorizations_session_id_idx" ON "agent_authorizations"("session_id"); + +-- CreateIndex +CREATE INDEX "agent_authorizations_expires_at_idx" ON "agent_authorizations"("expires_at"); + +-- CreateIndex +CREATE UNIQUE INDEX "agent_connections_token_digest_key" ON "agent_connections"("token_digest"); + +-- CreateIndex +CREATE UNIQUE INDEX "agent_connections_refresh_digest_key" ON "agent_connections"("refresh_digest"); + +-- CreateIndex +CREATE INDEX "agent_connections_client_id_idx" ON "agent_connections"("client_id"); + +-- CreateIndex +CREATE INDEX "agent_connections_external_identity_id_idx" ON "agent_connections"("external_identity_id"); + +-- CreateIndex +CREATE INDEX "agent_connections_provider_revision_id_idx" ON "agent_connections"("provider_revision_id"); + +-- CreateIndex +CREATE INDEX "agent_connections_membership_id_external_identity_id_create_idx" ON "agent_connections"("membership_id", "external_identity_id", "created_at"); + +-- AddForeignKey +ALTER TABLE "agent_authorizations" ADD CONSTRAINT "agent_authorizations_client_id_fkey" FOREIGN KEY ("client_id") REFERENCES "agent_clients"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "agent_authorizations" ADD CONSTRAINT "agent_authorizations_session_id_fkey" FOREIGN KEY ("session_id") REFERENCES "hub_sessions"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "agent_connections" ADD CONSTRAINT "agent_connections_client_id_fkey" FOREIGN KEY ("client_id") REFERENCES "agent_clients"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "agent_connections" ADD CONSTRAINT "agent_connections_membership_id_fkey" FOREIGN KEY ("membership_id") REFERENCES "memberships"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "agent_connections" ADD CONSTRAINT "agent_connections_external_identity_id_fkey" FOREIGN KEY ("external_identity_id") REFERENCES "external_identities"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "agent_connections" ADD CONSTRAINT "agent_connections_provider_revision_id_fkey" FOREIGN KEY ("provider_revision_id") REFERENCES "authentication_provider_revisions"("id") ON DELETE CASCADE ON UPDATE CASCADE; From de7b91c9353f915d7f89ce36e22ecbfe523e3844 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 22:57:16 -0800 Subject: [PATCH 04/17] feat(hub): host the learning MCP server behind agent sign-in Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25291e01-0146-42cb-ac6d-f5e1dd5c35f5 --- hub/server/create-app/index.ts | 4 + .../create-agent-connections/index.ts | 213 ++++++++++++++++++ .../create-learning-mcp-backend/index.ts | 191 ++++++++++++++++ hub/server/index.ts | 11 + .../express/canvas-sign-in-return/index.ts | 3 +- .../learning/load-learning-mcp/index.test.ts | 16 ++ .../learning/load-learning-mcp/index.ts | 33 +++ .../mcp/create-agent-auth-router/index.ts | 121 ++++++++++ .../mcp/handle-mcp-request/index.test.ts | 41 ++++ .../mcp/handle-mcp-request/index.ts | 24 ++ .../mcp/require-agent-token/index.ts | 25 ++ .../claim-agent-authorization/index.ts | 36 +++ .../create-agent-authorization/index.ts | 10 + .../decide-agent-authorization/index.ts | 18 ++ .../index.ts | 18 ++ .../find-pending-agent-authorization/index.ts | 17 ++ .../create-agent-client/index.ts | 8 + .../agent-clients/find-agent-client/index.ts | 8 + .../create-agent-connection/index.ts | 11 + .../find-agent-repository/index.ts | 20 ++ .../list-agent-connections/index.ts | 19 ++ .../record-agent-connection-audit/index.ts | 26 +++ .../revoke-agent-connection/index.ts | 17 ++ .../rotate-agent-connection/index.ts | 40 ++++ .../touch-agent-connection/index.ts | 24 ++ .../routes/agent-connections/index.db.test.ts | 178 +++++++++++++++ hub/server/routes/agent-connections/index.ts | 202 +++++++++++++++++ hub/server/routes/agent-connections/types.ts | 10 + .../present-security-audit/index.ts | 2 + hub/server/routes/index.ts | 11 + hub/server/routes/types.ts | 2 + hub/server/run-api/index.ts | 4 + hub/server/start-server-processes/index.ts | 2 + 33 files changed, 1364 insertions(+), 1 deletion(-) create mode 100644 hub/server/domains/agent-connections/create-agent-connections/index.ts create mode 100644 hub/server/domains/agent-connections/create-learning-mcp-backend/index.ts create mode 100644 hub/server/integrations/learning/load-learning-mcp/index.test.ts create mode 100644 hub/server/integrations/learning/load-learning-mcp/index.ts create mode 100644 hub/server/integrations/mcp/create-agent-auth-router/index.ts create mode 100644 hub/server/integrations/mcp/handle-mcp-request/index.test.ts create mode 100644 hub/server/integrations/mcp/handle-mcp-request/index.ts create mode 100644 hub/server/integrations/mcp/require-agent-token/index.ts create mode 100644 hub/server/repositories/agent-authorizations/claim-agent-authorization/index.ts create mode 100644 hub/server/repositories/agent-authorizations/create-agent-authorization/index.ts create mode 100644 hub/server/repositories/agent-authorizations/decide-agent-authorization/index.ts create mode 100644 hub/server/repositories/agent-authorizations/find-agent-authorization-challenge/index.ts create mode 100644 hub/server/repositories/agent-authorizations/find-pending-agent-authorization/index.ts create mode 100644 hub/server/repositories/agent-clients/create-agent-client/index.ts create mode 100644 hub/server/repositories/agent-clients/find-agent-client/index.ts create mode 100644 hub/server/repositories/agent-connections/create-agent-connection/index.ts create mode 100644 hub/server/repositories/agent-connections/find-agent-repository/index.ts create mode 100644 hub/server/repositories/agent-connections/list-agent-connections/index.ts create mode 100644 hub/server/repositories/agent-connections/record-agent-connection-audit/index.ts create mode 100644 hub/server/repositories/agent-connections/revoke-agent-connection/index.ts create mode 100644 hub/server/repositories/agent-connections/rotate-agent-connection/index.ts create mode 100644 hub/server/repositories/agent-connections/touch-agent-connection/index.ts create mode 100644 hub/server/routes/agent-connections/index.db.test.ts create mode 100644 hub/server/routes/agent-connections/index.ts create mode 100644 hub/server/routes/agent-connections/types.ts diff --git a/hub/server/create-app/index.ts b/hub/server/create-app/index.ts index 9d3f48b7..a679be7f 100644 --- a/hub/server/create-app/index.ts +++ b/hub/server/create-app/index.ts @@ -11,6 +11,7 @@ import type { CreateAppOptions } from "./types.ts" /** Give every endpoint the same request logging and safe error responses. */ export function createApp({ + agentConnections, agentVisualCritic, authentication, broadcast, @@ -35,8 +36,10 @@ export function createApp({ app.use( [ "/api/canvas", + "/api/agent-connections", "/api/auth", "/canvas/pair", + "/agents/approve", "/api/administrators", "/api/copilot-connection", "/api/session-revocation", @@ -57,6 +60,7 @@ export function createApp({ ) routes(app, { + agentConnections, agentVisualCritic, authentication, broadcast, diff --git a/hub/server/domains/agent-connections/create-agent-connections/index.ts b/hub/server/domains/agent-connections/create-agent-connections/index.ts new file mode 100644 index 00000000..533218b7 --- /dev/null +++ b/hub/server/domains/agent-connections/create-agent-connections/index.ts @@ -0,0 +1,213 @@ +import type { PrismaClient } from "../../../generated/prisma/client.ts" +import { claimAgentAuthorization } from "../../../repositories/agent-authorizations/claim-agent-authorization/index.ts" +import { createAgentAuthorization } from "../../../repositories/agent-authorizations/create-agent-authorization/index.ts" +import { decideAgentAuthorization } from "../../../repositories/agent-authorizations/decide-agent-authorization/index.ts" +import { findAgentAuthorizationChallenge } from "../../../repositories/agent-authorizations/find-agent-authorization-challenge/index.ts" +import { findPendingAgentAuthorization } from "../../../repositories/agent-authorizations/find-pending-agent-authorization/index.ts" +import { createAgentClient } from "../../../repositories/agent-clients/create-agent-client/index.ts" +import { findAgentClient } from "../../../repositories/agent-clients/find-agent-client/index.ts" +import { createAgentConnection } from "../../../repositories/agent-connections/create-agent-connection/index.ts" +import { listAgentConnections } from "../../../repositories/agent-connections/list-agent-connections/index.ts" +import { recordAgentConnectionAudit } from "../../../repositories/agent-connections/record-agent-connection-audit/index.ts" +import { revokeAgentConnection } from "../../../repositories/agent-connections/revoke-agent-connection/index.ts" +import { rotateAgentConnection } from "../../../repositories/agent-connections/rotate-agent-connection/index.ts" +import { touchAgentConnection } from "../../../repositories/agent-connections/touch-agent-connection/index.ts" +import { + canvasAuthorityReference, + readCanvasAuthority, +} from "../../../repositories/canvas/authority/index.ts" +import type { CanvasBrowser } from "../../canvas/authorization/index.ts" +import { + accessLifetime, + canvasDigest, + canvasSecret, + inactiveLifetime, + pairingLifetime, +} from "../../canvas/credentials/index.ts" + +const accessPattern = /^ra_[A-Za-z0-9_-]{43}$/ +const refreshPattern = /^rar_[A-Za-z0-9_-]{43}$/ +const codePattern = /^rac_[A-Za-z0-9_-]{43}$/ + +function issueTokens() { + const accessToken = canvasSecret("ra_") + const refreshToken = canvasSecret("rar_") + const now = Date.now() + return { + accessToken, + refreshToken, + tokenDigest: canvasDigest(accessToken), + refreshDigest: canvasDigest(refreshToken), + expiresAt: new Date(now + accessLifetime), + inactiveAt: new Date(now + inactiveLifetime), + } +} + +function tokenResponse(tokens: ReturnType) { + return { + access_token: tokens.accessToken, + token_type: "Bearer", + expires_in: Math.floor(accessLifetime / 1000), + refresh_token: tokens.refreshToken, + } +} + +/** + * Lets a person connect a coding agent to Hub with OAuth. A connection acts for the person + * who approved it, so every use rechecks that their Hub sign-in still holds. Only digests + * of codes and tokens are stored. + */ +export function createAgentConnections(database: PrismaClient) { + return { + async registerClient(client: { id: string; name: string; redirectUris: string[] }) { + return createAgentClient(database, client) + }, + + getClient(id: string) { + return findAgentClient(database, id) + }, + + async startAuthorization(input: { + clientId: string + redirectUri: string + codeChallenge: string + state?: string + }) { + const { id } = await createAgentAuthorization(database, { + ...input, + expiresAt: new Date(Date.now() + pairingLifetime), + }) + return id + }, + + async readAuthorization(id: string) { + const pending = await findPendingAgentAuthorization(database, id) + return pending && { clientName: pending.client.name, expiresAt: pending.expiresAt } + }, + + async decideAuthorization(id: string, browser: CanvasBrowser, approve: boolean) { + const pending = await findPendingAgentAuthorization(database, id) + if (!pending) return null + const redirect = new URL(pending.redirectUri) + const code = canvasSecret("rac_") + const decided = await database.$transaction(async (transaction) => { + const settled = await decideAgentAuthorization( + transaction, + id, + approve ? { sessionId: browser.sessionId, codeDigest: canvasDigest(code) } : null, + ) + if (settled && approve) { + await recordAgentConnectionAudit(transaction, { + action: "agent_connection.approve", + actorMembershipId: browser.viewer.membershipId, + authorizationId: id, + }) + } + return settled + }) + if (!decided) return null + if (approve) redirect.searchParams.set("code", code) + else redirect.searchParams.set("error", "access_denied") + if (pending.state !== null) redirect.searchParams.set("state", pending.state) + return redirect.toString() + }, + + async challenge(clientId: string, code: string) { + if (!codePattern.test(code)) return null + const found = await findAgentAuthorizationChallenge(database, clientId, canvasDigest(code)) + return found?.codeChallenge ?? null + }, + + async exchangeCode(clientId: string, code: string, redirectUri?: string) { + if (!codePattern.test(code)) return null + return database.$transaction(async (transaction) => { + const claimed = await claimAgentAuthorization(transaction, clientId, canvasDigest(code)) + const session = claimed?.session + if (!claimed || !session || (redirectUri && redirectUri !== claimed.redirectUri)) + return null + if (session.endedAt || session.expiresAt <= new Date()) return null + const reference = canvasAuthorityReference(session) + const viewer = reference && (await readCanvasAuthority(transaction, reference)) + if (!viewer) return null + const tokens = issueTokens() + await createAgentConnection(transaction, { + clientId, + membershipId: viewer.membershipId, + externalIdentityId: viewer.externalIdentityId, + providerRevisionId: viewer.providerRevisionId, + revocationRevision: viewer.revocationRevision, + tokenDigest: tokens.tokenDigest, + refreshDigest: tokens.refreshDigest, + expiresAt: tokens.expiresAt, + inactiveAt: tokens.inactiveAt, + }) + return tokenResponse(tokens) + }) + }, + + async refresh(clientId: string, refreshToken: string) { + if (!refreshPattern.test(refreshToken)) return null + const tokens = issueTokens() + return database.$transaction(async (transaction) => { + const connection = await rotateAgentConnection(transaction, { + clientId, + refreshDigest: canvasDigest(refreshToken), + tokenDigest: tokens.tokenDigest, + nextRefreshDigest: tokens.refreshDigest, + expiresAt: tokens.expiresAt, + inactiveAt: tokens.inactiveAt, + }) + const reference = connection && canvasAuthorityReference(connection) + const viewer = reference && (await readCanvasAuthority(transaction, reference)) + if (!viewer) return null + return tokenResponse(tokens) + }) + }, + + /** Returns who the token acts for, or null when it or their Hub access has ended. */ + async verify(accessToken: string) { + if (!accessPattern.test(accessToken)) return null + const connection = await touchAgentConnection( + database, + canvasDigest(accessToken), + new Date(Date.now() + inactiveLifetime), + ) + const reference = connection && canvasAuthorityReference(connection) + const viewer = reference && (await readCanvasAuthority(database, reference)) + return connection && viewer ? { connection, viewer } : null + }, + + async revokeToken(clientId: string, token: string) { + if (accessPattern.test(token)) + await revokeAgentConnection(database, { clientId, tokenDigest: canvasDigest(token) }) + else if (refreshPattern.test(token)) + await revokeAgentConnection(database, { clientId, refreshDigest: canvasDigest(token) }) + }, + + list(browser: CanvasBrowser) { + const { membershipId, externalIdentityId } = browser.viewer + return listAgentConnections(database, { membershipId, externalIdentityId }) + }, + + revokeBrowser(id: string, browser: CanvasBrowser) { + const { membershipId, externalIdentityId } = browser.viewer + return database.$transaction(async (transaction) => { + const revoked = await revokeAgentConnection(transaction, { + id, + membershipId, + externalIdentityId, + }) + if (!revoked) return false + await recordAgentConnectionAudit(transaction, { + action: "agent_connection.revoke", + actorMembershipId: membershipId, + connectionId: revoked.id, + }) + return true + }) + }, + } +} + +export type AgentConnections = ReturnType +export type AgentViewer = NonNullable>>["viewer"] diff --git a/hub/server/domains/agent-connections/create-learning-mcp-backend/index.ts b/hub/server/domains/agent-connections/create-learning-mcp-backend/index.ts new file mode 100644 index 00000000..20018d24 --- /dev/null +++ b/hub/server/domains/agent-connections/create-learning-mcp-backend/index.ts @@ -0,0 +1,191 @@ +import { access, mkdtemp, rm, writeFile } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join, resolve } from "node:path" + +import { runLearningCommand } from "../../../integrations/learning/run-learning-command/index.ts" +import { LearningCommandError } from "../../../integrations/learning/run-learning-command/errors.ts" +import { validatePrivateStorageRoot } from "../../../utils/validate-private-storage-root/index.ts" +import { learningStoreArguments } from "../../learning/learning-store-arguments/index.ts" + +interface LearningSettings { + applicationRoot?: string + cliPath: string + learningDatabaseUrl?: string + nodePath: string + root: string + staticDirectories: string[] +} + +interface StoredLearning { + record: { id: string; state: string } + status: { recallEligible: boolean } + withheld: boolean +} + +/** + * Answers one agent's learning tools for one repository by running the replica-learning + * command, the same way the Learnings page does. Each call names the connection as the + * agent, so records show which connection received or used guidance. + */ +export function createLearningMcpBackend(input: { + connectionId: string + learning: LearningSettings + learningsUrl: string + repository: { id: string; githubRepositoryId: bigint } + toAgentError: (code: string, message: string) => Error +}) { + const { learning, repository, toAgentError } = input + const actor = `agent:hub-connection-${input.connectionId}` + + async function storeDirectory() { + const applicationRoot = learning.applicationRoot ?? process.cwd() + const directory = await validatePrivateStorageRoot( + resolve(learning.root, "repositories", repository.id), + { + applicationRoot, + excludedDirectories: learning.staticDirectories, + name: "REPLICA_LEARNING_ROOT", + publicRoot: resolve(applicationRoot, "public"), + }, + ) + if (learning.learningDatabaseUrl) return directory + try { + await access(resolve(directory, "config.json")) + return directory + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error + return null + } + } + + async function run(directory: string, arguments_: string[]) { + try { + return await runLearningCommand( + [ + ...arguments_, + "--actor", + actor, + ...learningStoreArguments({ + directory, + repositoryId: repository.id, + repositoryScope: `github.com/repositories/${repository.githubRepositoryId}`, + }), + ], + { + cliPath: learning.cliPath, + nodePath: learning.nodePath, + ...(learning.learningDatabaseUrl + ? { learningDatabaseUrl: learning.learningDatabaseUrl } + : {}), + }, + ) + } catch (error) { + // The command writes its messages for people, so agents may see them. + if (error instanceof LearningCommandError) throw toAgentError(error.code, error.message) + throw error + } + } + + function sessionArguments(session?: { id: string; label?: string }) { + if (!session) return [] + return [ + "--session-id", + session.id, + ...(session.label === undefined ? [] : ["--session-label", session.label]), + ] + } + + return { + async getGuidance({ + task, + limit, + session, + }: { + task?: string + limit?: number + session?: { id: string; label?: string } + }) { + const directory = await storeDirectory() + if (!directory) return { guidanceId: null, text: "", learnings: [] } + const result = (await run(directory, [ + "recall", + ...(task === undefined ? [] : ["--task", task]), + "--limit", + String(limit ?? 20), + ...sessionArguments(session), + ])) as { + guidanceId: string + text: string + memories: { id: string; deliveryId: string }[] + } + // Only the framed text was recorded as delivered, so the raw learnings stay out. + return { + guidanceId: result.guidanceId, + text: result.text, + learnings: result.memories.map(({ id, deliveryId }) => ({ id, deliveryId })), + } + }, + + async reportUsage(report: { used: { before?: unknown; after?: unknown }[] }) { + if (report.used.some((item) => item.before !== undefined || item.after !== undefined)) + throw toAgentError( + "unsupported", + "Hub does not accept screenshots yet. Report usage without them.", + ) + const directory = await storeDirectory() + if (!directory) + throw toAgentError("not_found", "This repository has no learnings to report on.") + const folder = await mkdtemp(join(tmpdir(), "replica-agent-report-")) + try { + const file = join(folder, "report.json") + await writeFile(file, JSON.stringify(report), { mode: 0o600 }) + return await run(directory, ["report-usage", file]) + } finally { + await rm(folder, { recursive: true, force: true }) + } + }, + + submitSession() { + return Promise.reject( + toAgentError( + "grant_inactive", + "Hub does not collect agent sessions yet, so this session was not stored.", + ), + ) + }, + + async listLearnings({ state }: { state?: string[] }) { + const directory = await storeDirectory() + if (!directory) return [] + return run(directory, [ + "memories", + "--purpose", + "instruction", + ...(state ?? []).flatMap((value) => ["--state", value]), + ]) + }, + + async getLearning({ id }: { id: string }) { + const directory = await storeDirectory() + if (!directory) throw toAgentError("not_found", `Learning ${id} was not found.`) + const item = (await run(directory, [ + "show", + id, + "--purpose", + "instruction", + ])) as StoredLearning + const { record } = item + if (record.state === "accepted" && !item.withheld && item.status.recallEligible) return item + // A learning no one accepted is not guidance, so its text stays with people. + const summary = { id: record.id, state: record.state, withheld: true } + if (record.state !== "proposed") return summary + return { + ...summary, + decide: { + note: "Only a person can decide. Ask a repository administrator to accept or reject it on the Hub Learnings page.", + url: input.learningsUrl, + }, + } + }, + } +} diff --git a/hub/server/index.ts b/hub/server/index.ts index d8663308..cc079e2f 100644 --- a/hub/server/index.ts +++ b/hub/server/index.ts @@ -34,6 +34,7 @@ import { startServerProcesses } from "./start-server-processes/index.ts" import { parseRuntimeConfig } from "./utils/parse-runtime-config/index.ts" import { getJobProcessors } from "./workers/configuration.ts" import { runJobWorker } from "./workers/run-job-worker/index.ts" +import type { AgentConnectionRouteDependencies } from "./routes/agent-connections/types.ts" import type { AuthenticationRouteDependencies } from "./routes/api/auth/types.ts" import type { AgentVisualCriticRouteDependencies } from "./routes/api/canvas/decision-model/types.ts" import type { CopilotConnectionRouteDependencies } from "./routes/api/copilot-connection/types.ts" @@ -79,6 +80,7 @@ try { } const trustedProxyHops = runsApi ? configuredTrustedProxyHops : 0 let authentication: AuthenticationRouteDependencies | undefined + let agentConnections: AgentConnectionRouteDependencies | undefined let agentVisualCritic: AgentVisualCriticRouteDependencies | undefined let copilotConnection: CopilotConnectionRouteDependencies | undefined let decisionModels: DecisionModelRouteDependencies | undefined @@ -184,6 +186,13 @@ try { { scopeGitHubMembers: authenticationConfiguration.githubConfigured }, ) learnings = learningDependencies + const agentApplicationOrigin = authenticationEnvironment.HUB_APPLICATION_ORIGIN + if (learningConfiguration && agentApplicationOrigin) { + agentConnections = { + applicationOrigin: agentApplicationOrigin, + learning: learningConfiguration, + } + } if (decisionRuntimeConfiguration) { const applicationOrigin = authenticationEnvironment.HUB_APPLICATION_ORIGIN if (!storage || !learningConfiguration || !applicationOrigin) { @@ -369,6 +378,7 @@ try { await runApi({ ...configuration, logger, + agentConnections, agentVisualCritic, isReady: isStorageReady, authentication, @@ -391,6 +401,7 @@ try { ...configuration, databaseUrl, logger, + agentConnections, agentVisualCritic, isStorageReady, authentication, diff --git a/hub/server/integrations/express/canvas-sign-in-return/index.ts b/hub/server/integrations/express/canvas-sign-in-return/index.ts index 3f8cfe99..862f7ed8 100644 --- a/hub/server/integrations/express/canvas-sign-in-return/index.ts +++ b/hub/server/integrations/express/canvas-sign-in-return/index.ts @@ -4,7 +4,8 @@ import type { Request } from "express" import { readCookie } from "../read-cookie/index.ts" export const canvasSignInReturnCookie = "replica_canvas_sign_in_return" -export const canvasSignInReturnPattern = /^\/canvas\/(?:pair\/[A-F0-9]{10}|connections)(?![\s\S])/ +export const canvasSignInReturnPattern = + /^\/(?:canvas\/(?:pair\/[A-F0-9]{10}|connections)|agents\/approve\/[0-9a-f-]{36})(?![\s\S])/ function bindingDigest(browserBinding: string) { return createHash("sha256").update(browserBinding).digest("hex") diff --git a/hub/server/integrations/learning/load-learning-mcp/index.test.ts b/hub/server/integrations/learning/load-learning-mcp/index.test.ts new file mode 100644 index 00000000..a137cdac --- /dev/null +++ b/hub/server/integrations/learning/load-learning-mcp/index.test.ts @@ -0,0 +1,16 @@ +import { fileURLToPath } from "node:url" +import { expect, it } from "vitest" + +import { loadLearningMcp } from "." + +it("loads the learning tools that sit beside the configured command", async () => { + const cliPath = fileURLToPath( + new URL("../../../../../packages/learning/bin/replica-learning.mjs", import.meta.url), + ) + + const mcp = await loadLearningMcp(cliPath) + + expect(new mcp.LearningError("not_found", "Missing.")).toMatchObject({ code: "not_found" }) + const server = mcp.createLearningMcpServer({}) + await server.close() +}) diff --git a/hub/server/integrations/learning/load-learning-mcp/index.ts b/hub/server/integrations/learning/load-learning-mcp/index.ts new file mode 100644 index 00000000..138336c1 --- /dev/null +++ b/hub/server/integrations/learning/load-learning-mcp/index.ts @@ -0,0 +1,33 @@ +import { dirname, resolve } from "node:path" +import { pathToFileURL } from "node:url" + +export interface LearningMcpServer { + connect(transport: unknown): Promise + close(): Promise +} + +export interface LearningMcp { + createLearningMcpServer( + backend: Record Promise>, + options?: { name?: string; version?: string; onError?: (error: unknown) => void }, + ): LearningMcpServer + LearningError: new (code: string, message: string) => Error +} + +const loaded = new Map>() + +/** + * Loads the learning tools from the installed replica-learning package, so Hub offers + * agents the same tools and instructions as the local server. The package's MCP SDK is + * optional, which is why it loads only when an agent first connects. + */ +export function loadLearningMcp(cliPath: string) { + const url = pathToFileURL(resolve(dirname(cliPath), "../src/mcp.mjs")).href + let module = loaded.get(url) + if (!module) { + module = import(url) as Promise + module.catch(() => loaded.delete(url)) + loaded.set(url, module) + } + return module +} diff --git a/hub/server/integrations/mcp/create-agent-auth-router/index.ts b/hub/server/integrations/mcp/create-agent-auth-router/index.ts new file mode 100644 index 00000000..831e183a --- /dev/null +++ b/hub/server/integrations/mcp/create-agent-auth-router/index.ts @@ -0,0 +1,121 @@ +import type { RequestHandler } from "express" +import { mcpAuthRouter } from "@modelcontextprotocol/sdk/server/auth/router.js" +import { + InvalidGrantError, + InvalidTokenError, +} from "@modelcontextprotocol/sdk/server/auth/errors.js" +import type { OAuthServerProvider } from "@modelcontextprotocol/sdk/server/auth/provider.js" +import type { OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js" + +export interface AgentOAuthService { + registerClient(client: { id: string; name: string; redirectUris: string[] }): Promise + getClient(id: string): Promise<{ id: string; name: string; redirectUris: string[] } | null> + startAuthorization(input: { + clientId: string + redirectUri: string + codeChallenge: string + state?: string + }): Promise + challenge(clientId: string, code: string): Promise + exchangeCode(clientId: string, code: string, redirectUri?: string): Promise + refresh(clientId: string, refreshToken: string): Promise + verify(accessToken: string): Promise<{ + connection: { id: string; clientId: string; expiresAt: Date } + } | null> + revokeToken(clientId: string, token: string): Promise +} + +export const agentMcpPath = "/mcp" + +function clientInformation(client: { id: string; name: string; redirectUris: string[] }) { + return { + client_id: client.id, + client_name: client.name, + redirect_uris: client.redirectUris, + grant_types: ["authorization_code", "refresh_token"], + response_types: ["code"], + token_endpoint_auth_method: "none", + } +} + +/** Adapts Hub's agent connections to the SDK's OAuth provider contract. */ +export function agentOAuthProvider(service: AgentOAuthService): OAuthServerProvider { + return { + clientsStore: { + getClient: async (id) => { + if (!/^[0-9a-f-]{36}$/i.test(id)) return undefined + const client = await service.getClient(id) + return client ? clientInformation(client) : undefined + }, + // Agents run on people's machines and cannot keep a secret, so every client is + // public and relies on PKCE. + registerClient: async (metadata) => { + const client = { + id: (metadata as { client_id?: string }).client_id ?? crypto.randomUUID(), + name: (metadata.client_name ?? "Coding agent").slice(0, 200), + redirectUris: metadata.redirect_uris.map(String), + } + await service.registerClient(client) + return { + ...clientInformation(client), + client_id_issued_at: Math.floor(Date.now() / 1000), + } + }, + }, + async authorize(client, params, response) { + const id = await service.startAuthorization({ + clientId: client.client_id, + redirectUri: params.redirectUri, + codeChallenge: params.codeChallenge, + ...(params.state === undefined ? {} : { state: params.state }), + }) + response.redirect(302, `/agents/approve/${id}`) + }, + async challengeForAuthorizationCode(client, code) { + const challenge = await service.challenge(client.client_id, code) + if (!challenge) throw new InvalidGrantError("The authorization code is invalid or expired.") + return challenge + }, + async exchangeAuthorizationCode(client, code, _verifier, redirectUri) { + const tokens = await service.exchangeCode(client.client_id, code, redirectUri) + if (!tokens) throw new InvalidGrantError("The authorization code is invalid or expired.") + return tokens + }, + async exchangeRefreshToken(client, refreshToken) { + const tokens = await service.refresh(client.client_id, refreshToken) + if (!tokens) throw new InvalidGrantError("The refresh token is invalid or expired.") + return tokens + }, + async verifyAccessToken(token) { + const result = await service.verify(token) + if (!result) throw new InvalidTokenError("The access token is invalid or expired.") + const { connection } = result + return { + token, + clientId: connection.clientId, + scopes: [], + expiresAt: Math.floor(connection.expiresAt.getTime() / 1000), + extra: { result }, + } + }, + async revokeToken(client, request) { + await service.revokeToken(client.client_id, request.token) + }, + } +} + +/** + * Serves OAuth discovery, client registration, sign-in and token endpoints, so agents + * that support MCP authorization can connect with only Hub's MCP URL. + */ +export function createAgentAuthRouter( + applicationOrigin: string, + service: AgentOAuthService, +): RequestHandler { + return mcpAuthRouter({ + provider: agentOAuthProvider(service), + issuerUrl: new URL(applicationOrigin), + resourceServerUrl: new URL(agentMcpPath, applicationOrigin), + resourceName: "Replica Hub learnings", + }) +} diff --git a/hub/server/integrations/mcp/handle-mcp-request/index.test.ts b/hub/server/integrations/mcp/handle-mcp-request/index.test.ts new file mode 100644 index 00000000..bcf3b4e2 --- /dev/null +++ b/hub/server/integrations/mcp/handle-mcp-request/index.test.ts @@ -0,0 +1,41 @@ +import { once } from "node:events" +import type { AddressInfo } from "node:net" +import express from "express" +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js" +import { expect, it, onTestFinished } from "vitest" + +import { handleMcpRequest } from "." + +it("answers an MCP call whose body Express already parsed", async () => { + const app = express() + app.use(express.json()) + app.post("/mcp", async (request, response) => { + const server = new McpServer({ name: "test", version: "1.0.0" }) + server.registerTool("ping", { description: "Replies." }, () => ({ + content: [{ type: "text", text: "pong" }], + })) + await handleMcpRequest(server, request, response) + }) + const listener = app.listen(0, "127.0.0.1") + onTestFinished(() => void listener.close()) + await once(listener, "listening") + + const response = await fetch(`http://127.0.0.1:${(listener.address() as AddressInfo).port}/mcp`, { + method: "POST", + headers: { + Accept: "application/json, text/event-stream", + "Content-Type": "application/json", + }, + body: JSON.stringify({ + jsonrpc: "2.0", + id: 1, + method: "tools/call", + params: { name: "ping", arguments: {} }, + }), + }) + + expect(await response.json()).toMatchObject({ + id: 1, + result: { content: [{ type: "text", text: "pong" }] }, + }) +}) diff --git a/hub/server/integrations/mcp/handle-mcp-request/index.ts b/hub/server/integrations/mcp/handle-mcp-request/index.ts new file mode 100644 index 00000000..7330ec46 --- /dev/null +++ b/hub/server/integrations/mcp/handle-mcp-request/index.ts @@ -0,0 +1,24 @@ +import type { Request, Response } from "express" +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js" + +interface McpServer { + connect(transport: StreamableHTTPServerTransport): Promise + close(): Promise +} + +/** + * Answers one MCP request with a fresh server. Nothing is kept between requests, so a + * revoked connection or lost access takes effect on the next call. + */ +export async function handleMcpRequest(server: McpServer, request: Request, response: Response) { + const transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: undefined, + enableJsonResponse: true, + }) + response.on("close", () => { + void transport.close() + void server.close() + }) + await server.connect(transport) + await transport.handleRequest(request, response, request.body) +} diff --git a/hub/server/integrations/mcp/require-agent-token/index.ts b/hub/server/integrations/mcp/require-agent-token/index.ts new file mode 100644 index 00000000..49916f07 --- /dev/null +++ b/hub/server/integrations/mcp/require-agent-token/index.ts @@ -0,0 +1,25 @@ +import type { RequestHandler } from "express" +import { requireBearerAuth } from "@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js" +import { getOAuthProtectedResourceMetadataUrl } from "@modelcontextprotocol/sdk/server/auth/router.js" + +import { + agentMcpPath, + agentOAuthProvider, + type AgentOAuthService, +} from "../create-agent-auth-router/index.ts" + +/** + * Rejects requests without a live agent token. The response points agents at Hub's OAuth + * metadata, which is how they learn to start sign-in. + */ +export function requireAgentToken( + applicationOrigin: string, + service: AgentOAuthService, +): RequestHandler { + return requireBearerAuth({ + verifier: agentOAuthProvider(service), + resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl( + new URL(agentMcpPath, applicationOrigin), + ), + }) +} diff --git a/hub/server/repositories/agent-authorizations/claim-agent-authorization/index.ts b/hub/server/repositories/agent-authorizations/claim-agent-authorization/index.ts new file mode 100644 index 00000000..59225725 --- /dev/null +++ b/hub/server/repositories/agent-authorizations/claim-agent-authorization/index.ts @@ -0,0 +1,36 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +/** Uses an approved code exactly once, even when two exchanges race. */ +export async function claimAgentAuthorization( + database: Pick, + clientId: string, + codeDigest: string, +) { + const now = new Date() + const [claimed] = await database.agentAuthorization.updateManyAndReturn({ + where: { + clientId, + codeDigest, + approvedAt: { not: null }, + consumedAt: null, + expiresAt: { gt: now }, + }, + data: { consumedAt: now }, + select: { + id: true, + redirectUri: true, + session: { + select: { + id: true, + membershipId: true, + externalIdentityId: true, + providerRevisionId: true, + revocationRevision: true, + endedAt: true, + expiresAt: true, + }, + }, + }, + }) + return claimed ?? null +} diff --git a/hub/server/repositories/agent-authorizations/create-agent-authorization/index.ts b/hub/server/repositories/agent-authorizations/create-agent-authorization/index.ts new file mode 100644 index 00000000..1d871f18 --- /dev/null +++ b/hub/server/repositories/agent-authorizations/create-agent-authorization/index.ts @@ -0,0 +1,10 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +/** Drops expired requests first, so abandoned sign-ins do not pile up. */ +export async function createAgentAuthorization( + database: Pick, + data: Prisma.AgentAuthorizationUncheckedCreateInput, +) { + await database.agentAuthorization.deleteMany({ where: { expiresAt: { lte: new Date() } } }) + return database.agentAuthorization.create({ data, select: { id: true } }) +} diff --git a/hub/server/repositories/agent-authorizations/decide-agent-authorization/index.ts b/hub/server/repositories/agent-authorizations/decide-agent-authorization/index.ts new file mode 100644 index 00000000..87b71db3 --- /dev/null +++ b/hub/server/repositories/agent-authorizations/decide-agent-authorization/index.ts @@ -0,0 +1,18 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +/** + * Settles a pending request once. Approval binds the person's session and stores only + * the code's digest; cancelling uses the request up so it cannot be approved later. + */ +export async function decideAgentAuthorization( + database: Pick, + id: string, + decision: { sessionId: string; codeDigest: string } | null, +) { + const now = new Date() + const result = await database.agentAuthorization.updateMany({ + where: { id, expiresAt: { gt: now }, approvedAt: null, consumedAt: null }, + data: decision ? { ...decision, approvedAt: now } : { consumedAt: now }, + }) + return result.count === 1 +} diff --git a/hub/server/repositories/agent-authorizations/find-agent-authorization-challenge/index.ts b/hub/server/repositories/agent-authorizations/find-agent-authorization-challenge/index.ts new file mode 100644 index 00000000..1707b01c --- /dev/null +++ b/hub/server/repositories/agent-authorizations/find-agent-authorization-challenge/index.ts @@ -0,0 +1,18 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +export function findAgentAuthorizationChallenge( + database: Pick, + clientId: string, + codeDigest: string, +) { + return database.agentAuthorization.findFirst({ + where: { + clientId, + codeDigest, + approvedAt: { not: null }, + consumedAt: null, + expiresAt: { gt: new Date() }, + }, + select: { codeChallenge: true }, + }) +} diff --git a/hub/server/repositories/agent-authorizations/find-pending-agent-authorization/index.ts b/hub/server/repositories/agent-authorizations/find-pending-agent-authorization/index.ts new file mode 100644 index 00000000..2e4d0ade --- /dev/null +++ b/hub/server/repositories/agent-authorizations/find-pending-agent-authorization/index.ts @@ -0,0 +1,17 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +export function findPendingAgentAuthorization( + database: Pick, + id: string, +) { + return database.agentAuthorization.findFirst({ + where: { id, expiresAt: { gt: new Date() }, approvedAt: null, consumedAt: null }, + select: { + id: true, + redirectUri: true, + state: true, + expiresAt: true, + client: { select: { name: true } }, + }, + }) +} diff --git a/hub/server/repositories/agent-clients/create-agent-client/index.ts b/hub/server/repositories/agent-clients/create-agent-client/index.ts new file mode 100644 index 00000000..316ae865 --- /dev/null +++ b/hub/server/repositories/agent-clients/create-agent-client/index.ts @@ -0,0 +1,8 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +export function createAgentClient( + database: Pick, + data: { id: string; name: string; redirectUris: string[] }, +) { + return database.agentClient.create({ data }) +} diff --git a/hub/server/repositories/agent-clients/find-agent-client/index.ts b/hub/server/repositories/agent-clients/find-agent-client/index.ts new file mode 100644 index 00000000..2c79388e --- /dev/null +++ b/hub/server/repositories/agent-clients/find-agent-client/index.ts @@ -0,0 +1,8 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +export function findAgentClient( + database: Pick, + id: string, +) { + return database.agentClient.findUnique({ where: { id } }) +} diff --git a/hub/server/repositories/agent-connections/create-agent-connection/index.ts b/hub/server/repositories/agent-connections/create-agent-connection/index.ts new file mode 100644 index 00000000..2dcb145f --- /dev/null +++ b/hub/server/repositories/agent-connections/create-agent-connection/index.ts @@ -0,0 +1,11 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +export function createAgentConnection( + database: Pick, + data: Prisma.AgentConnectionUncheckedCreateInput, +) { + return database.agentConnection.create({ + data, + select: { id: true, expiresAt: true }, + }) +} diff --git a/hub/server/repositories/agent-connections/find-agent-repository/index.ts b/hub/server/repositories/agent-connections/find-agent-repository/index.ts new file mode 100644 index 00000000..65e8945c --- /dev/null +++ b/hub/server/repositories/agent-connections/find-agent-repository/index.ts @@ -0,0 +1,20 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +/** Learnings belong to GitHub repositories, so agents can reach only those. */ +export function findAgentRepository( + database: Pick, + id: string, +) { + return database.repository.findFirst({ + where: { id, removedAt: null, localPath: null, githubRepositoryId: { not: null } }, + select: { + id: true, + canvasId: true, + githubRepositoryId: true, + nameWithOwner: true, + defaultBranch: true, + localPath: true, + removedAt: true, + }, + }) +} diff --git a/hub/server/repositories/agent-connections/list-agent-connections/index.ts b/hub/server/repositories/agent-connections/list-agent-connections/index.ts new file mode 100644 index 00000000..ebef9297 --- /dev/null +++ b/hub/server/repositories/agent-connections/list-agent-connections/index.ts @@ -0,0 +1,19 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +export function listAgentConnections( + database: Pick, + owner: { membershipId: string; externalIdentityId: string }, +) { + const now = new Date() + return database.agentConnection.findMany({ + where: { ...owner, revokedAt: null, inactiveAt: { gt: now } }, + orderBy: [{ createdAt: "desc" }, { id: "desc" }], + select: { + id: true, + createdAt: true, + lastUsedAt: true, + inactiveAt: true, + client: { select: { name: true } }, + }, + }) +} diff --git a/hub/server/repositories/agent-connections/record-agent-connection-audit/index.ts b/hub/server/repositories/agent-connections/record-agent-connection-audit/index.ts new file mode 100644 index 00000000..0a730ef5 --- /dev/null +++ b/hub/server/repositories/agent-connections/record-agent-connection-audit/index.ts @@ -0,0 +1,26 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +export function recordAgentConnectionAudit( + database: Pick, + input: { + action: "agent_connection.approve" | "agent_connection.revoke" + actorMembershipId: string + connectionId?: string + authorizationId?: string + }, +) { + const { action, actorMembershipId, connectionId, authorizationId } = input + return database.securityAudit.create({ + data: { + action, + outcome: "SUCCESS", + targetType: connectionId ? "agent_connection" : "agent_authorization", + targetId: connectionId ?? authorizationId ?? null, + context: { + actorMembershipId, + ...(connectionId ? { connectionId } : {}), + ...(authorizationId ? { authorizationId } : {}), + }, + }, + }) +} diff --git a/hub/server/repositories/agent-connections/revoke-agent-connection/index.ts b/hub/server/repositories/agent-connections/revoke-agent-connection/index.ts new file mode 100644 index 00000000..3c35abbe --- /dev/null +++ b/hub/server/repositories/agent-connections/revoke-agent-connection/index.ts @@ -0,0 +1,17 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +/** Ends one connection, found by either of its tokens or by its owner. */ +export async function revokeAgentConnection( + database: Pick, + where: + | { clientId: string; tokenDigest: string } + | { clientId: string; refreshDigest: string } + | { id: string; membershipId: string; externalIdentityId: string }, +) { + const [revoked] = await database.agentConnection.updateManyAndReturn({ + where: { ...where, revokedAt: null }, + data: { revokedAt: new Date() }, + select: { id: true, membershipId: true }, + }) + return revoked ?? null +} diff --git a/hub/server/repositories/agent-connections/rotate-agent-connection/index.ts b/hub/server/repositories/agent-connections/rotate-agent-connection/index.ts new file mode 100644 index 00000000..e16b8a6e --- /dev/null +++ b/hub/server/repositories/agent-connections/rotate-agent-connection/index.ts @@ -0,0 +1,40 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +/** Replaces both tokens, so a stolen refresh token stops working after one use. */ +export async function rotateAgentConnection( + database: Pick, + input: { + clientId: string + refreshDigest: string + tokenDigest: string + nextRefreshDigest: string + expiresAt: Date + inactiveAt: Date + }, +) { + const now = new Date() + const [connection] = await database.agentConnection.updateManyAndReturn({ + where: { + clientId: input.clientId, + refreshDigest: input.refreshDigest, + revokedAt: null, + inactiveAt: { gt: now }, + }, + data: { + tokenDigest: input.tokenDigest, + refreshDigest: input.nextRefreshDigest, + expiresAt: input.expiresAt, + inactiveAt: input.inactiveAt, + lastUsedAt: now, + }, + select: { + id: true, + membershipId: true, + externalIdentityId: true, + providerRevisionId: true, + revocationRevision: true, + expiresAt: true, + }, + }) + return connection ?? null +} diff --git a/hub/server/repositories/agent-connections/touch-agent-connection/index.ts b/hub/server/repositories/agent-connections/touch-agent-connection/index.ts new file mode 100644 index 00000000..e66e59a5 --- /dev/null +++ b/hub/server/repositories/agent-connections/touch-agent-connection/index.ts @@ -0,0 +1,24 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +/** Finds the connection for an access token and pushes back its inactivity limit. */ +export async function touchAgentConnection( + database: Pick, + tokenDigest: string, + inactiveAt: Date, +) { + const now = new Date() + const [connection] = await database.agentConnection.updateManyAndReturn({ + where: { tokenDigest, revokedAt: null, expiresAt: { gt: now }, inactiveAt: { gt: now } }, + data: { lastUsedAt: now, inactiveAt }, + select: { + id: true, + clientId: true, + membershipId: true, + externalIdentityId: true, + providerRevisionId: true, + revocationRevision: true, + expiresAt: true, + }, + }) + return connection ?? null +} diff --git a/hub/server/routes/agent-connections/index.db.test.ts b/hub/server/routes/agent-connections/index.db.test.ts new file mode 100644 index 00000000..81908a6a --- /dev/null +++ b/hub/server/routes/agent-connections/index.db.test.ts @@ -0,0 +1,178 @@ +import { createHash, randomBytes } from "node:crypto" +import { once } from "node:events" +import { createServer } from "node:http" +import type { AddressInfo } from "node:net" +import { expect, it, vi } from "vitest" + +import { createApp } from "../../create-app" +import { createLogger } from "../../integrations/pino/create-logger" +import { prisma } from "../../integrations/prisma" +import { createAuthenticationRouteDependencies } from "../api/auth/create-authentication-route-dependencies" +import { createProductRouteDependencies } from "../api/product/create-product-route-dependencies" + +it("connects an agent with the person's approval and stops it after they revoke it", async () => { + const server = createServer() + try { + server.listen(0, "127.0.0.1") + await once(server, "listening") + const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}` + const authentication = await createAuthenticationRouteDependencies( + { + NODE_ENV: "development", + DATABASE_URL: process.env.DATABASE_URL, + HUB_LOCAL_SIGN_IN: "true", + HUB_APPLICATION_ORIGIN: origin, + HUB_AUTHENTICATION_ENCRYPTION_KEY: randomBytes(32).toString("base64"), + HUB_BOOTSTRAP_SECRET: "synthetic-bootstrap-secret-for-agent-test", + }, + () => { + throw new Error("The agent connection test must not reach an outside provider.") + }, + ) + const product = Object.assign(createProductRouteDependencies(), { + getRepositoryPermission: vi.fn(() => Promise.resolve("admin" as const)), + }) + const githubRepositoryId = BigInt(Math.floor(Math.random() * 1_000_000_000) + 1) + const repository = await prisma.repository.create({ + data: { + nameWithOwner: `octo/agent-${githubRepositoryId}`, + defaultBranch: "main", + githubRepositoryId, + }, + }) + server.on( + "request", + createApp({ + authentication, + product, + agentConnections: { + applicationOrigin: origin, + learning: { + cliPath: "/missing/cli.mjs", + nodePath: "node", + root: "/", + staticDirectories: [], + }, + }, + logger: createLogger({ level: "silent" }), + }), + ) + const mcpUrl = `${origin}/mcp/repositories/${repository.id}` + function callMcp(token?: string) { + return fetch(mcpUrl, { + method: "POST", + headers: { + Accept: "application/json, text/event-stream", + "Content-Type": "application/json", + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }, + body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }), + }) + } + + const unauthenticated = await callMcp() + expect(unauthenticated.status).toBe(401) + expect(unauthenticated.headers.get("www-authenticate")).toContain( + `${origin}/.well-known/oauth-protected-resource/mcp`, + ) + + expect( + await (await fetch(`${origin}/.well-known/oauth-protected-resource/mcp`)).json(), + ).toMatchObject({ resource: `${origin}/mcp`, authorization_servers: [`${origin}/`] }) + + const redirectUri = "http://127.0.0.1:9/callback" + const registered = (await ( + await fetch(`${origin}/register`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ client_name: "Test agent", redirect_uris: [redirectUri] }), + }) + ).json()) as { client_id: string; client_secret?: string } + expect(registered.client_secret).toBeUndefined() + + const verifier = randomBytes(32).toString("base64url") + const authorize = await fetch( + `${origin}/authorize?${new URLSearchParams({ + response_type: "code", + client_id: registered.client_id, + redirect_uri: redirectUri, + code_challenge: createHash("sha256").update(verifier).digest("base64url"), + code_challenge_method: "S256", + state: "agent-state", + })}`, + { redirect: "manual" }, + ) + const approvalPath = authorize.headers.get("location")! + expect(approvalPath).toMatch(/^\/agents\/approve\/[0-9a-f-]{36}$/) + const authorizationId = approvalPath.split("/").at(-1)! + const authorizationPath = `/api/agent-connections/authorizations/${authorizationId}` + expect((await fetch(origin + authorizationPath)).status).toBe(401) + + const start = await fetch(`${origin}/api/auth/local/start`, { + method: "POST", + redirect: "manual", + headers: { Origin: origin }, + body: new URLSearchParams({ return_to: approvalPath }), + }) + const callback = await fetch(new URL(start.headers.get("location")!, origin), { + redirect: "manual", + headers: { + Cookie: start.headers + .getSetCookie() + .map((cookie) => cookie.split(";", 1)[0]) + .join("; "), + }, + }) + expect(callback.headers.get("location")).toBe(approvalPath) + const session = callback.headers + .getSetCookie() + .find((cookie) => cookie.startsWith("hub_session="))! + .split(";", 1)[0]! + function browser(path: string, method = "GET") { + return fetch(origin + path, { method, headers: { Cookie: session, Origin: origin } }) + } + expect(await (await browser(authorizationPath)).json()).toMatchObject({ agent: "Test agent" }) + const { redirectUrl } = (await ( + await browser(`${authorizationPath}/approve`, "POST") + ).json()) as { redirectUrl: string } + const returned = new URL(redirectUrl) + expect(returned.searchParams.get("state")).toBe("agent-state") + expect((await browser(`${authorizationPath}/approve`, "POST")).status).toBe(410) + + const tokens = (await ( + await fetch(`${origin}/token`, { + method: "POST", + body: new URLSearchParams({ + grant_type: "authorization_code", + client_id: registered.client_id, + code: returned.searchParams.get("code")!, + code_verifier: verifier, + redirect_uri: redirectUri, + }), + }) + ).json()) as { access_token: string } + + // Local sign-in cannot read GitHub repositories, so the token works but access stops + // at the repository check. + expect((await callMcp(tokens.access_token)).status).toBe(403) + + const listed = (await (await browser("/api/agent-connections")).json()) as { + connections: { id: string; agent: string }[] + } + expect(listed.connections).toEqual([expect.objectContaining({ agent: "Test agent" })]) + const connectionId = listed.connections[0]!.id + expect((await browser(`/api/agent-connections/${connectionId}`, "DELETE")).status).toBe(204) + expect((await callMcp(tokens.access_token)).status).toBe(401) + expect( + await prisma.securityAudit.count({ + where: { action: { in: ["agent_connection.approve", "agent_connection.revoke"] } }, + }), + ).toBe(2) + } finally { + if (server.listening) { + await new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())) + }) + } + } +}, 20_000) diff --git a/hub/server/routes/agent-connections/index.ts b/hub/server/routes/agent-connections/index.ts new file mode 100644 index 00000000..f9b4475a --- /dev/null +++ b/hub/server/routes/agent-connections/index.ts @@ -0,0 +1,202 @@ +import express from "express" +import type { Request, RequestHandler, Response } from "express" +import type { Logger } from "pino" + +import { createAgentConnections } from "../../domains/agent-connections/create-agent-connections/index.ts" +import type { AgentConnections } from "../../domains/agent-connections/create-agent-connections/index.ts" +import { createLearningMcpBackend } from "../../domains/agent-connections/create-learning-mcp-backend/index.ts" +import { + createCanvasAuthorization, + type GetCanvasRepositoryPermission, +} from "../../domains/canvas/authorization/index.ts" +import { canvasDigest } from "../../domains/canvas/credentials/index.ts" +import { hubSessionCookieName } from "../../integrations/express/hub-session-cookie-name/index.ts" +import { readCookie } from "../../integrations/express/read-cookie/index.ts" +import { requireOrigin } from "../../integrations/express/require-origin/index.ts" +import { GitHubProviderRequestError } from "../../integrations/github/errors.ts" +import { loadLearningMcp } from "../../integrations/learning/load-learning-mcp/index.ts" +import { createAgentAuthRouter } from "../../integrations/mcp/create-agent-auth-router/index.ts" +import { handleMcpRequest } from "../../integrations/mcp/handle-mcp-request/index.ts" +import { requireAgentToken } from "../../integrations/mcp/require-agent-token/index.ts" +import { findAgentRepository } from "../../repositories/agent-connections/find-agent-repository/index.ts" +import type { AgentConnectionRouteDependencies } from "./types.ts" + +const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i + +function status(response: Response, code: number, error: string) { + response.status(code).json({ error }) +} + +/** + * Lets people connect coding agents to Hub and lets those agents read a repository's + * learnings over MCP. People approve and manage connections with their Hub sign-in; + * agents use OAuth tokens that act for the person who approved them. + */ +export function agentConnectionRoutes( + dependencies: AgentConnectionRouteDependencies, + getRepositoryPermission?: GetCanvasRepositoryPermission, + logger?: Logger, +) { + const { applicationOrigin, learning } = dependencies + const router = express.Router() + const browserMutation = requireOrigin(applicationOrigin) + + let services: Promise<{ + connections: AgentConnections + authority: ReturnType + prisma: Parameters[0] + }> | null = null + function load() { + services ??= import("../../integrations/prisma/index.ts").then(({ prisma }) => ({ + prisma, + connections: createAgentConnections(prisma), + authority: createCanvasAuthorization(prisma, getRepositoryPermission), + })) + return services + } + + // The SDK's router needs the service before any request, so each call loads it lazily. + const service: Parameters[1] = { + registerClient: async (client) => (await load()).connections.registerClient(client), + getClient: async (id) => (await load()).connections.getClient(id), + startAuthorization: async (input) => (await load()).connections.startAuthorization(input), + challenge: async (clientId, code) => (await load()).connections.challenge(clientId, code), + exchangeCode: async (clientId, code, redirectUri) => + (await load()).connections.exchangeCode(clientId, code, redirectUri), + refresh: async (clientId, token) => (await load()).connections.refresh(clientId, token), + verify: async (token) => (await load()).connections.verify(token), + revokeToken: async (clientId, token) => (await load()).connections.revokeToken(clientId, token), + } + + function handler( + handle: (request: Request, response: Response) => Promise, + ): RequestHandler { + return async (request, response, next) => { + try { + await handle(request, response) + } catch (error) { + if (error instanceof GitHubProviderRequestError) { + status(response, 503, "Repository access could not be verified. Try again.") + return + } + next(error) + } + } + } + + async function browser(request: Request) { + const cookie = readCookie(request, hubSessionCookieName) + return cookie ? (await load()).authority.browser(canvasDigest(cookie)) : null + } + + function decision(approve: boolean) { + return handler(async (request, response) => { + const id = String(request.params.authorizationId) + const session = await browser(request) + if (!session) return status(response, 401, "Sign in to continue.") + const redirectUrl = uuidPattern.test(id) + ? await (await load()).connections.decideAuthorization(id, session, approve) + : null + if (!redirectUrl) + return status(response, 410, "This request expired. Connect again from your agent.") + response.json({ redirectUrl }) + }) + } + + router.use(createAgentAuthRouter(applicationOrigin, service)) + + router.get( + "/api/agent-connections/authorizations/:authorizationId", + handler(async (request, response) => { + const id = String(request.params.authorizationId) + const session = await browser(request) + if (!session) return status(response, 401, "Sign in to continue.") + const pending = uuidPattern.test(id) + ? await (await load()).connections.readAuthorization(id) + : null + if (!pending) + return status(response, 410, "This request expired. Connect again from your agent.") + response.json({ + agent: pending.clientName, + signedInAs: session.viewer.login, + expiresAt: pending.expiresAt.toISOString(), + }) + }), + ) + router.post( + "/api/agent-connections/authorizations/:authorizationId/approve", + browserMutation, + decision(true), + ) + router.post( + "/api/agent-connections/authorizations/:authorizationId/cancel", + browserMutation, + decision(false), + ) + router.get( + "/api/agent-connections", + handler(async (request, response) => { + const session = await browser(request) + if (!session) return status(response, 401, "Sign in to continue.") + const connections = await (await load()).connections.list(session) + response.json({ + connections: connections.map((connection) => ({ + id: connection.id, + agent: connection.client.name, + createdAt: connection.createdAt.toISOString(), + lastUsedAt: connection.lastUsedAt?.toISOString() ?? null, + inactiveAt: connection.inactiveAt.toISOString(), + })), + }) + }), + ) + router.delete( + "/api/agent-connections/:connectionId", + browserMutation, + handler(async (request, response) => { + const session = await browser(request) + if (!session) return status(response, 401, "Sign in to continue.") + const id = String(request.params.connectionId) + const revoked = + uuidPattern.test(id) && (await (await load()).connections.revokeBrowser(id, session)) + if (!revoked) return status(response, 404, "Agent connection was not found.") + response.status(204).end() + }), + ) + + const mcpPath = "/mcp/repositories/:repositoryId" + router.post( + mcpPath, + requireAgentToken(applicationOrigin, service), + handler(async (request, response) => { + const id = String(request.params.repositoryId) + const { prisma, authority } = await load() + const repository = uuidPattern.test(id) ? await findAgentRepository(prisma, id) : null + if (!repository?.githubRepositoryId) return status(response, 404, "Repository not found.") + const { result } = request.auth!.extra as { + result: NonNullable>> + } + if ((await authority.permission(result.viewer, repository)) === "none") + return status(response, 403, "Repository access was denied.") + const mcp = await loadLearningMcp(learning.cliPath) + const backend = createLearningMcpBackend({ + connectionId: result.connection.id, + learning, + learningsUrl: new URL(`/repositories/${repository.id}/learnings`, applicationOrigin).href, + repository: { id: repository.id, githubRepositoryId: repository.githubRepositoryId }, + toAgentError: (code, message) => new mcp.LearningError(code, message), + }) + const server = mcp.createLearningMcpServer(backend, { + name: "replica-hub-learning", + onError: (error) => logger?.error({ err: error }, "Agent learning tool failed"), + }) + await handleMcpRequest(server, request, response) + }), + ) + router.all(mcpPath, (_request, response) => { + response.set("Allow", "POST") + status(response, 405, "Send MCP messages with POST.") + }) + + return router +} diff --git a/hub/server/routes/agent-connections/types.ts b/hub/server/routes/agent-connections/types.ts new file mode 100644 index 00000000..2c99be9e --- /dev/null +++ b/hub/server/routes/agent-connections/types.ts @@ -0,0 +1,10 @@ +export interface AgentConnectionRouteDependencies { + applicationOrigin: string + learning: { + cliPath: string + learningDatabaseUrl?: string + nodePath: string + root: string + staticDirectories: string[] + } +} diff --git a/hub/server/routes/api/security-audits/present-security-audit/index.ts b/hub/server/routes/api/security-audits/present-security-audit/index.ts index 4986bd55..8d14f63b 100644 --- a/hub/server/routes/api/security-audits/present-security-audit/index.ts +++ b/hub/server/routes/api/security-audits/present-security-audit/index.ts @@ -77,6 +77,8 @@ function actorFor(record: SecurityAuditListRecord) { case "canvas_connection.renew": case "canvas_connection.revoke": case "canvas_connection.activity": + case "agent_connection.approve": + case "agent_connection.revoke": case "analytics_destination.create": case "analytics_destination.update": case "analytics_destination.pause": diff --git a/hub/server/routes/index.ts b/hub/server/routes/index.ts index 3ea782d4..4020e484 100644 --- a/hub/server/routes/index.ts +++ b/hub/server/routes/index.ts @@ -80,11 +80,13 @@ import { post as handleDecisionTrainingCancelPost } from "./api/decision-model/t import { post as handleDecisionCandidatePromotionPost } from "./api/decision-model/candidates/promotion/post/index.ts" import { post as handleDecisionCandidateRejectionPost } from "./api/decision-model/candidates/rejection/post/index.ts" import { post as handleDecisionRollbackPost } from "./api/decision-model/rollback/post/index.ts" +import { agentConnectionRoutes } from "./agent-connections/index.ts" import { post as handleDecisionBuildEvaluationPost } from "./api/decision-model/builds/evaluation/post/index.ts" /** Keep endpoint registration separate from the app's shared middleware. */ export function routes(app: Express, dependencies: RouteDependencies = {}): void { const { + agentConnections, agentVisualCritic, authentication, copilotConnection, @@ -143,6 +145,15 @@ export function routes(app: Express, dependencies: RouteDependencies = {}): void "/api/canvas", canvasRoutes(authentication.signOut.applicationOrigin, product, agentVisualCritic), ) + if (agentConnections) { + app.use( + agentConnectionRoutes( + agentConnections, + product.getRepositoryPermission?.bind(product), + logger, + ), + ) + } if (product.analytics) mountRepositoryAnalytics( app, diff --git a/hub/server/routes/types.ts b/hub/server/routes/types.ts index 6b56a78e..646e3f97 100644 --- a/hub/server/routes/types.ts +++ b/hub/server/routes/types.ts @@ -12,8 +12,10 @@ import type { PrivatePreviewRouteDependencies } from "./private-preview/types.ts import type { GitHubSetupRouteDependencies } from "./api/settings/github/types.ts" import type { DecisionModelRouteDependencies } from "./api/decision-model/types.ts" import type { AgentVisualCriticRouteDependencies } from "./api/canvas/decision-model/types.ts" +import type { AgentConnectionRouteDependencies } from "./agent-connections/types.ts" export interface RouteDependencies { + agentConnections?: AgentConnectionRouteDependencies agentVisualCritic?: AgentVisualCriticRouteDependencies authentication?: AuthenticationRouteDependencies copilotConnection?: CopilotConnectionRouteDependencies diff --git a/hub/server/run-api/index.ts b/hub/server/run-api/index.ts index a9ca213b..9f904806 100644 --- a/hub/server/run-api/index.ts +++ b/hub/server/run-api/index.ts @@ -9,6 +9,7 @@ import type { AgentVisualCriticRouteDependencies } from "../routes/api/canvas/de import type { CopilotConnectionRouteDependencies } from "../routes/api/copilot-connection/types.ts" import type { DecisionModelRouteDependencies } from "../routes/api/decision-model/types.ts" import type { GitHubWebhookRouteDependencies } from "../routes/api/github/webhooks/types.ts" +import type { AgentConnectionRouteDependencies } from "../routes/agent-connections/types.ts" import type { LearningsRouteDependencies } from "../routes/api/learnings/types.ts" import type { ProductRouteDependencies } from "../routes/api/product/types.ts" import type { PublicSharingRouteDependencies } from "../routes/api/public-sharing/types.ts" @@ -26,6 +27,7 @@ import { shutdownServer } from "../shutdown-server/index.ts" export async function runApi({ port, logger, + agentConnections, agentVisualCritic, authentication, githubSetup, @@ -47,6 +49,7 @@ export async function runApi({ }: { port: number logger: Logger + agentConnections?: AgentConnectionRouteDependencies agentVisualCritic?: AgentVisualCriticRouteDependencies authentication?: AuthenticationRouteDependencies copilotConnection?: CopilotConnectionRouteDependencies @@ -92,6 +95,7 @@ export async function runApi({ "request", createApp({ logger, + agentConnections, agentVisualCritic, broadcast: realtime.broadcast, clientDirectory, diff --git a/hub/server/start-server-processes/index.ts b/hub/server/start-server-processes/index.ts index b067e434..0297d5a7 100644 --- a/hub/server/start-server-processes/index.ts +++ b/hub/server/start-server-processes/index.ts @@ -6,6 +6,7 @@ import type { AgentVisualCriticRouteDependencies } from "../routes/api/canvas/de import type { CopilotConnectionRouteDependencies } from "../routes/api/copilot-connection/types.ts" import type { DecisionModelRouteDependencies } from "../routes/api/decision-model/types.ts" import type { GitHubWebhookRouteDependencies } from "../routes/api/github/webhooks/types.ts" +import type { AgentConnectionRouteDependencies } from "../routes/agent-connections/types.ts" import type { LearningsRouteDependencies } from "../routes/api/learnings/types.ts" import type { ProductRouteDependencies } from "../routes/api/product/types.ts" import type { PublicSharingRouteDependencies } from "../routes/api/public-sharing/types.ts" @@ -26,6 +27,7 @@ export async function startServerProcesses(options: { onDemandConcurrency: number scheduledConcurrency: number isStorageReady?: () => Promise + agentConnections?: AgentConnectionRouteDependencies agentVisualCritic?: AgentVisualCriticRouteDependencies authentication?: AuthenticationRouteDependencies copilotConnection?: CopilotConnectionRouteDependencies From 2aa7afc60dd86474aed88729b42a4693288a75d6 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 22:57:16 -0800 Subject: [PATCH 05/17] feat(hub): let people approve and revoke agent connections Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25291e01-0146-42cb-ac6d-f5e1dd5c35f5 --- .../application/hub-application/index.tsx | 8 +- .../hub/agent-connections/contract.ts | 23 +++ hub/client/application/hub/routes.ts | 1 + .../hub/routes/agent-approval/index.tsx | 86 +++++++++++ .../hub/routes/learning-agents/index.tsx | 103 +++++++++++++ .../application/hub/routes/product-routes.ts | 1 + .../routes/real-workspace-navigation.test.tsx | 20 +++ .../view-models/settings-learnings/index.ts | 1 + .../agent-connections-page/index.test.tsx | 141 ++++++------------ .../pages/agent-connections-page/index.tsx | 114 +++++++------- .../pages/agent-connections-page/stories.tsx | 60 ++++---- .../pages/agent-connections-page/styles.css | 11 +- .../pages/agent-connections-page/types.ts | 30 ++-- hub/client/pages/learnings-page/index.tsx | 21 ++- hub/client/pages/learnings-page/stories.tsx | 1 + hub/client/pages/learnings-page/styles.css | 6 + hub/client/pages/learnings-page/types.ts | 1 + 17 files changed, 409 insertions(+), 219 deletions(-) create mode 100644 hub/client/application/hub/agent-connections/contract.ts create mode 100644 hub/client/application/hub/routes/agent-approval/index.tsx create mode 100644 hub/client/application/hub/routes/learning-agents/index.tsx diff --git a/hub/client/application/hub-application/index.tsx b/hub/client/application/hub-application/index.tsx index 5e67638e..ff0cca24 100644 --- a/hub/client/application/hub-application/index.tsx +++ b/hub/client/application/hub-application/index.tsx @@ -197,9 +197,11 @@ export function HubApplication({ canvasReturnTo }: { canvasReturnTo?: string } = : null, badge: "Collaborative prototyping", badgeAlternate: "Built for feedback", - description: canvasReturnTo - ? "Sign in to continue to your Replica canvas connection." - : "Sign in with an active Replica Hub membership.", + description: canvasReturnTo?.startsWith("/agents/") + ? "Sign in to connect your coding agent to Replica Hub." + : canvasReturnTo + ? "Sign in to continue to your Replica canvas connection." + : "Sign in with an active Replica Hub membership.", footerNote: "\u00a9 2026 GitHub, Inc.", heading: "Build and review prototypes with your team.", notice: null, diff --git a/hub/client/application/hub/agent-connections/contract.ts b/hub/client/application/hub/agent-connections/contract.ts new file mode 100644 index 00000000..b9f0ef32 --- /dev/null +++ b/hub/client/application/hub/agent-connections/contract.ts @@ -0,0 +1,23 @@ +import { z } from "zod" + +export const agentAuthorizationSchema = z + .object({ agent: z.string().min(1), signedInAs: z.string().min(1), expiresAt: z.iso.datetime() }) + .strict() + +export const agentDecisionSchema = z.object({ redirectUrl: z.url() }).strict() + +export const agentConnectionsSchema = z + .object({ + connections: z.array( + z + .object({ + id: z.uuid(), + agent: z.string().min(1), + createdAt: z.iso.datetime(), + lastUsedAt: z.iso.datetime().nullable(), + inactiveAt: z.iso.datetime(), + }) + .strict(), + ), + }) + .strict() diff --git a/hub/client/application/hub/routes.ts b/hub/client/application/hub/routes.ts index 57fb007a..4818cc8a 100644 --- a/hub/client/application/hub/routes.ts +++ b/hub/client/application/hub/routes.ts @@ -8,6 +8,7 @@ export default [ route("signed-in/no-access", "routes/no-repository-access/index.tsx"), route("sign-in", "routes/sign-in/index.tsx"), route("canvas/pair/:userCode", "routes/canvas-pairing/index.tsx"), + route("agents/approve/:authorizationId", "routes/agent-approval/index.tsx"), route("shared/:shareId", "routes/product-public/index.tsx"), ...standaloneSetupRoutes, layout("routes/workspace/index.tsx", [ diff --git a/hub/client/application/hub/routes/agent-approval/index.tsx b/hub/client/application/hub/routes/agent-approval/index.tsx new file mode 100644 index 00000000..998a37be --- /dev/null +++ b/hub/client/application/hub/routes/agent-approval/index.tsx @@ -0,0 +1,86 @@ +import { redirect, useFetcher, useLocation } from "react-router" +import { z } from "zod" + +import { HubApplication } from "@application/hub-application" +import { + agentAuthorizationSchema, + agentDecisionSchema, +} from "@application/hub/agent-connections/contract" +import { canvasActionError } from "@application/hub/canvas-connections/contract" +import { FormBoundary } from "@application/hub/form-boundary" +import { ApiRequestError } from "@application/hub/requests/api-request-error" +import { requestJson } from "@application/hub/requests/request-json" +import { AgentConnectionsPage } from "@pages/agent-connections-page" +import type { AgentConnectionsPageData } from "@pages/agent-connections-page/types" + +import type { Route } from "./+types/index" + +function authorizationPath(value: string | undefined) { + const id = z.uuid().safeParse(value) + if (!id.success) throw new Response("This agent request is invalid.", { status: 404 }) + return { id: id.data, browserPath: `/agents/approve/${id.data}` } +} + +export async function clientLoader({ request, params }: Route.ClientLoaderArgs) { + const { id, browserPath } = authorizationPath(params.authorizationId) + try { + const authorization = await requestJson( + new URL(`/api/agent-connections/authorizations/${id}`, request.url), + agentAuthorizationSchema, + { signal: request.signal }, + ) + const page: AgentConnectionsPageData = { + view: "approval", + requestingAgent: authorization.agent, + signedInAs: authorization.signedInAs, + expiresLabel: `This request expires at ${new Date(authorization.expiresAt).toLocaleTimeString()}.`, + decisionPath: browserPath, + } + return { page, browserPath } + } catch (error) { + if (error instanceof ApiRequestError && error.status === 401) return { page: null, browserPath } + if (error instanceof ApiRequestError && error.status === 410) + throw new Response(error.message, { status: 410 }) + throw error + } +} + +export async function clientAction({ request, params }: Route.ClientActionArgs) { + const { id, browserPath } = authorizationPath(params.authorizationId) + if (request.method !== "POST") throw new Response("Method not allowed.", { status: 405 }) + const decision = (await request.formData()).get("decision") + if (decision !== "approve" && decision !== "cancel") + throw new Response("Choose whether to approve this agent.", { status: 422 }) + try { + const { redirectUrl } = await requestJson( + new URL(`/api/agent-connections/authorizations/${id}/${decision}`, request.url), + agentDecisionSchema, + { method: "POST", signal: request.signal }, + ) + // The agent listens on its own address, so the browser leaves Hub to finish. + return redirect(redirectUrl) + } catch (error) { + if (error instanceof ApiRequestError && error.status === 401) return redirect(browserPath) + return canvasActionError(error) + } +} + +export function meta() { + return [{ title: "Connect an agent - Replica Hub" }] +} + +export default function AgentApproval({ loaderData }: Route.ComponentProps) { + const fetcher = useFetcher<{ error?: string }>() + const { pathname } = useLocation() + if (!loaderData.page) return + const busy = fetcher.state !== "idle" + return ( + void fetcher.submit(form, { method: "post", action: pathname })} + > + + + ) +} diff --git a/hub/client/application/hub/routes/learning-agents/index.tsx b/hub/client/application/hub/routes/learning-agents/index.tsx new file mode 100644 index 00000000..e19333e1 --- /dev/null +++ b/hub/client/application/hub/routes/learning-agents/index.tsx @@ -0,0 +1,103 @@ +import { useFetcher, useLocation, useOutletContext } from "react-router" +import { z } from "zod" + +import { agentConnectionsSchema } from "@application/hub/agent-connections/contract" +import { + canvasActionError, + canvasFormDestination, +} from "@application/hub/canvas-connections/contract" +import { recordIdentifierSchema } from "@application/hub/contracts" +import type { WorkspaceResponse } from "@application/hub/contracts/types" +import { FormBoundary } from "@application/hub/form-boundary" +import { requestJson } from "@application/hub/requests/request-json" +import { AgentConnectionsPage } from "@pages/agent-connections-page" + +import type { Route } from "./+types/index" +import type { WorkspaceRouteHandle } from "../workspace/types" + +export const handle = { workspaceSection: "learnings" } satisfies WorkspaceRouteHandle + +function repositoryId(value: string | undefined) { + const parsed = recordIdentifierSchema.safeParse(value) + if (!parsed.success) throw new Response("Invalid repository identifier.", { status: 400 }) + return parsed.data +} + +function dateLabel(value: string) { + return new Date(value).toLocaleDateString() +} + +export async function clientLoader({ request, params }: Route.ClientLoaderArgs) { + const id = repositoryId(params.repositoryId) + const { connections } = await requestJson( + new URL("/api/agent-connections", request.url), + agentConnectionsSchema, + { signal: request.signal }, + ) + return { + mcpUrl: new URL(`/mcp/repositories/${id}`, request.url).href, + connections: connections.map((connection) => ({ + id: connection.id, + name: connection.agent, + connectedLabel: `Connected ${dateLabel(connection.createdAt)}`, + lastUsedLabel: connection.lastUsedAt + ? `Last used ${dateLabel(connection.lastUsedAt)}` + : "Not used yet", + revokePath: `/repositories/${id}/learnings/agents/${connection.id}`, + })), + } +} + +export async function clientAction({ request, params }: Route.ClientActionArgs) { + const id = repositoryId(params.repositoryId) + if (request.method !== "POST") throw new Response("Method not allowed.", { status: 405 }) + const form = await request.formData() + const destination = canvasFormDestination(form, request.url) + const connectionId = destination?.pathname.startsWith(`/repositories/${id}/learnings/agents/`) + ? z.uuid().safeParse(destination.pathname.split("/").at(-1)) + : null + if (!connectionId?.success || form.get("_method") !== "delete") { + throw new Response("This agent connection could not be revoked.", { status: 422 }) + } + try { + await requestJson( + new URL(`/api/agent-connections/${connectionId.data}`, request.url), + z.undefined(), + { method: "DELETE", signal: request.signal }, + ) + } catch (error) { + return canvasActionError(error) + } + return { notice: "Agent access revoked." } +} + +export function meta() { + return [{ title: "Connect an agent - Replica Hub" }] +} + +export default function LearningAgents({ loaderData, params }: Route.ComponentProps) { + const workspace = useOutletContext() + const fetcher = useFetcher<{ error?: string; notice?: string }>() + const { pathname } = useLocation() + const busy = fetcher.state !== "idle" + const repository = workspace?.repositories.find(({ id }) => id === params.repositoryId) + return ( + void fetcher.submit(form, { method: "post", action: pathname })} + > + + + ) +} diff --git a/hub/client/application/hub/routes/product-routes.ts b/hub/client/application/hub/routes/product-routes.ts index 0d0b79f6..1e987514 100644 --- a/hub/client/application/hub/routes/product-routes.ts +++ b/hub/client/application/hub/routes/product-routes.ts @@ -11,6 +11,7 @@ export const repositoryProductRoutes: RouteConfigEntry[] = [ route("prototypes/:prototypeId/share-links", "routes/product-share-links/index.tsx"), route("analytics", "routes/settings-analytics/index.tsx"), route("learnings", "routes/settings-learnings/index.tsx"), + route("learnings/agents", "routes/learning-agents/index.tsx"), ] export const workspaceProductRoutes: RouteConfigEntry[] = [ diff --git a/hub/client/application/hub/routes/real-workspace-navigation.test.tsx b/hub/client/application/hub/routes/real-workspace-navigation.test.tsx index 761f0a9c..83feabcf 100644 --- a/hub/client/application/hub/routes/real-workspace-navigation.test.tsx +++ b/hub/client/application/hub/routes/real-workspace-navigation.test.tsx @@ -1336,6 +1336,26 @@ describe("real workspace navigation", () => { expect(screen.queryByRole("link", { name: "Prototypes" })).not.toBeInTheDocument() }) + it("returns to an agent's approval request after sign-in", async () => { + const path = "/agents/approve/7c9e6679-7425-40de-944b-e07fc1f90ae7" + await renderApplication(path, [ + json("/api/auth/providers", { providers: ["github"] }), + ...[ + "/api/auth/session", + "/api/agent-connections/authorizations/7c9e6679-7425-40de-944b-e07fc1f90ae7", + ].map((endpoint) => + http.get(`${window.location.origin}${endpoint}`, () => + Response.json({ error: "Sign in to continue." }, { status: 401 }), + ), + ), + ]) + + const signIn = await screen.findByRole("button", { + name: "Sign in with GitHub", + }) + expect(new FormData(signIn.form ?? undefined).get("return_to")).toBe(path) + }) + it("shows a disabled picker and Prototypes without Create on a repository-free landing", async () => { await renderApplication("/repositories", workspaceApi([])) diff --git a/hub/client/application/hub/view-models/settings-learnings/index.ts b/hub/client/application/hub/view-models/settings-learnings/index.ts index e8146c27..45bf18c4 100644 --- a/hub/client/application/hub/view-models/settings-learnings/index.ts +++ b/hub/client/application/hub/view-models/settings-learnings/index.ts @@ -334,6 +334,7 @@ export function settingsLearnings( ? null : `Copilot used ${formatCredits(state.usageCredits)} for this repository in the last 30 days.`, }, + agentsPath: `/repositories/${repositoryId}/learnings/agents`, run: { path: `/repositories/${repositoryId}/learnings/runs`, available: state.permissions.requestRun && state.runAvailable, diff --git a/hub/client/pages/agent-connections-page/index.test.tsx b/hub/client/pages/agent-connections-page/index.test.tsx index 69c2c23d..9471050e 100644 --- a/hub/client/pages/agent-connections-page/index.test.tsx +++ b/hub/client/pages/agent-connections-page/index.test.tsx @@ -3,26 +3,25 @@ import { describe, expect, it, vi } from "vitest" import { HubThemeProvider } from "@hooks/use-hub-theme" -import { AgentConnectionsPrototype } from "." -import type { AgentConnectionsPrototypeData } from "./types" +import { AgentConnectionsPage } from "." -function renderPrototype(data: AgentConnectionsPrototypeData) { - render(, { wrapper: HubThemeProvider }) -} - -describe("AgentConnectionsPrototype()", () => { - it("copies a repository MCP endpoint without putting a credential in the config", async () => { +describe("AgentConnectionsPage()", () => { + it("copies a repository MCP address without putting a credential in the config", async () => { const writeText = vi.fn().mockResolvedValue(undefined) vi.stubGlobal("navigator", { ...navigator, clipboard: { writeText } }) - const data: AgentConnectionsPrototypeData = { - repositoryId: "2001", - repositoryName: "github/prototype", - hubUrl: "https://hub.example.com", - signedInAs: "@octocat", - view: "connections", - connections: [], - } - renderPrototype(data) + render( + , + { wrapper: HubThemeProvider }, + ) const config = screen.getByLabelText("Hub MCP configuration") expect(config).toHaveTextContent("https://hub.example.com/mcp/repositories/2001") @@ -35,83 +34,41 @@ describe("AgentConnectionsPrototype()", () => { expect(writeText).toHaveBeenCalledWith(config.textContent) }) - it("requires confirmation and revokes only the selected agent connection", () => { - const data: AgentConnectionsPrototypeData = { - repositoryId: "2001", - repositoryName: "github/prototype", - hubUrl: "https://hub.example.com", - signedInAs: "@octocat", - view: "connections", - connections: [ - { - id: "agent-vscode", - name: "Visual Studio Code", - connectedAt: "2026-11-18", - lastUsedAt: "2026-11-24", - }, - { - id: "agent-local", - name: "Local MCP client", - connectedAt: "2026-11-12", - lastUsedAt: "2026-11-21", - }, - ], - } - renderPrototype(data) - - fireEvent.click(screen.getByRole("button", { name: "Revoke Visual Studio Code access" })) - const dialog = screen.getByRole("dialog", { name: "Revoke agent access?" }) - expect(dialog).toHaveTextContent("does not sign you out of Hub") - expect(within(dialog).getByRole("button", { name: "Cancel" })).toBeVisible() - - fireEvent.click(within(dialog).getByRole("button", { name: "Revoke access" })) - - expect(screen.queryByText("Visual Studio Code")).not.toBeInTheDocument() - expect(screen.getByText("Local MCP client")).toBeVisible() - expect(screen.getByRole("region", { name: "Notifications" })).toHaveTextContent( - "Visual Studio Code can no longer access Hub.", - ) - expect(document.activeElement).toBe( - screen.getByRole("heading", { name: "Your connected agents" }), + it("asks for confirmation before revoking only the chosen agent", () => { + render( + , + { wrapper: HubThemeProvider }, ) - }) - - it("keeps agent access pending until approval and separates screenshot consent", () => { - const data: AgentConnectionsPrototypeData = { - repositoryId: "2001", - repositoryName: "github/prototype", - hubUrl: "https://hub.example.com", - signedInAs: "@octocat", - view: "approval", - requestingAgent: "Visual Studio Code", - connections: [], - } - renderPrototype(data) - expect(screen.getByText(/does not allow session-message storage/)).toBeVisible() - expect(screen.queryByRole("heading", { name: "Agent connected" })).not.toBeInTheDocument() - fireEvent.click(screen.getByRole("button", { name: "Approve access" })) - - expect(screen.getByRole("heading", { name: "Agent connected" })).toBeVisible() - expect(screen.getByText(/revoke its Hub access at any time/)).toBeVisible() - }) + fireEvent.click(screen.getByRole("button", { name: "Revoke Local MCP client access" })) - it("does not connect the agent when the person cancels approval", () => { - const data: AgentConnectionsPrototypeData = { - repositoryId: "2001", - repositoryName: "github/prototype", - hubUrl: "https://hub.example.com", - signedInAs: "@octocat", - view: "approval", - requestingAgent: "Visual Studio Code", - connections: [], - } - renderPrototype(data) - - fireEvent.click(screen.getByRole("button", { name: "Cancel" })) - - expect(screen.getByRole("heading", { name: "Connection cancelled" })).toBeVisible() - expect(screen.queryByRole("heading", { name: "Agent connected" })).not.toBeInTheDocument() - expect(screen.getByText(/No Hub access was granted/)).toBeVisible() + const dialog = screen.getByRole("dialog", { name: "Revoke agent access?" }) + const form = within(dialog).getByRole("button", { name: "Revoke access" }).closest("form") + expect(form).toHaveAttribute("action", "/repositories/2001/learnings/agents/agent-local") + expect(new FormData(form!).get("_method")).toBe("delete") }) }) diff --git a/hub/client/pages/agent-connections-page/index.tsx b/hub/client/pages/agent-connections-page/index.tsx index 8fbc4ea3..72e93aae 100644 --- a/hub/client/pages/agent-connections-page/index.tsx +++ b/hub/client/pages/agent-connections-page/index.tsx @@ -5,68 +5,56 @@ import { CanvasDialog } from "@components/prototype-canvas-dialog" import { CopyableCodeBlock } from "@components/copyable-code-block" import { HubToast } from "@components/hub-toast" -import type { AgentConnectionsPrototypeData } from "./types" +import type { AgentConnectionsPageData } from "./types" import "./styles.css" -export function AgentConnectionsPrototype({ data }: { data: AgentConnectionsPrototypeData }) { - const [connections, setConnections] = useState(data.connections) +/** + * Lets people approve a coding agent's request to use their Hub access, and review or + * revoke the agents they already connected. + */ +export function AgentConnectionsPage({ + data, + busy = false, +}: { + data: AgentConnectionsPageData + busy?: boolean +}) { const [connectionToRevoke, setConnectionToRevoke] = useState(null) - const [notice, setNotice] = useState("") - const [approval, setApproval] = useState<"pending" | "approved" | "cancelled">("pending") const connectionsHeadingRef = useRef(null) - const endpoint = `${data.hubUrl.replace(/\/$/, "")}/mcp/repositories/${data.repositoryId}` - const configuration = JSON.stringify({ mcpServers: { replica: { url: endpoint } } }, null, 2) - const selectedConnection = connections.find(({ id }) => id === connectionToRevoke) - - function revokeConnection() { - if (!selectedConnection) return - setConnections((current) => current.filter(({ id }) => id !== selectedConnection.id)) - setConnectionToRevoke(null) - setNotice(`${selectedConnection.name} can no longer access Hub.`) - } if (data.view === "approval") { return (

- {approval === "pending" ? ( -
- - Connect {data.requestingAgent} to Hub? - - - You are signed in as {data.signedInAs}. This agent can read guidance - and report which learnings it applied for repositories you can access. Hub checks - access on every request; only people can accept or change learnings. - - - This does not allow session-message storage, screenshot storage, or automated - screenshot review. Those choices require separate consent. - -
- - -
-
- ) : ( -
- - {approval === "approved" ? "Agent connected" : "Connection cancelled"} - - - {approval === "approved" - ? `Return to ${data.requestingAgent} to continue. You can revoke its Hub access at any time.` - : `You can close this page and return to ${data.requestingAgent}. No Hub access was granted.`} - -
- )} +
+ + Connect {data.requestingAgent} to Hub? + + + You are signed in as @{data.signedInAs}. This agent can read guidance + and report which learnings it applied for repositories you can access. Hub checks access + on every request; only people can accept or change learnings. + + + This does not allow session-message storage, screenshot storage, or automated screenshot + review. Those choices require separate consent. + + {data.expiresLabel} +
+ + +
+
) } + const configuration = JSON.stringify({ mcpServers: { replica: { url: data.mcpUrl } } }, null, 2) + const selectedConnection = data.connections.find(({ id }) => id === connectionToRevoke) + return (
@@ -95,24 +83,22 @@ export function AgentConnectionsPrototype({ data }: { data: AgentConnectionsProt Your connected agents - Connected as {data.signedInAs}. These agents can use your Hub access for any repository + Connected as @{data.signedInAs}. These agents can use your Hub access for any repository you can access. - {connections.length ? ( + {data.connections.length ? (
    - {connections.map((connection) => ( + {data.connections.map((connection) => (
  • {connection.name} - Connected{" "} - - {" · "}Last used{" "} - + {connection.connectedLabel} · {connection.lastUsedLabel}
    -
- + ) : null} - {notice ? : null} + {data.notice ? : null} ) } diff --git a/hub/client/pages/agent-connections-page/stories.tsx b/hub/client/pages/agent-connections-page/stories.tsx index 56775d47..d940e1d5 100644 --- a/hub/client/pages/agent-connections-page/stories.tsx +++ b/hub/client/pages/agent-connections-page/stories.tsx @@ -5,8 +5,8 @@ import type { RepositoryWorkspaceData } from "@features/repository-workspace/typ import { authenticatedHeaderData } from "@/storybook/fixtures/authenticated-header" import { githubEmpty, githubPrototype } from "@/storybook/fixtures/repositories" -import { AgentConnectionsPrototype } from "." -import type { AgentConnectionsPrototypeData } from "./types" +import { AgentConnectionsPage } from "." +import type { AgentConnectionsPageData } from "./types" const workspace: RepositoryWorkspaceData = { ...authenticatedHeaderData, @@ -30,48 +30,52 @@ const workspace: RepositoryWorkspaceData = { welcomePath: "/welcome", } -const connections: AgentConnectionsPrototypeData = { - repositoryId: "2001", - repositoryName: "github/prototype", - hubUrl: "https://hub.example.com", - signedInAs: "@octocat", +const connections: AgentConnectionsPageData = { view: "connections", + repositoryName: "github/prototype", + mcpUrl: "https://hub.example.com/mcp/repositories/2001", + signedInAs: "octocat", + notice: null, connections: [ { id: "agent-vscode", name: "Visual Studio Code", - connectedAt: "2026-11-18", - lastUsedAt: "2026-11-24", + connectedLabel: "Connected 11/18/2026", + lastUsedLabel: "Last used 11/24/2026", + revokePath: "/repositories/2001/learnings/agents/agent-vscode", }, { id: "agent-local", name: "Local MCP client", - connectedAt: "2026-11-12", - lastUsedAt: "2026-11-21", + connectedLabel: "Connected 11/12/2026", + lastUsedLabel: "Not used yet", + revokePath: "/repositories/2001/learnings/agents/agent-local", }, ], } -const approval: AgentConnectionsPrototypeData = { - ...connections, +const approval: AgentConnectionsPageData = { view: "approval", requestingAgent: "Visual Studio Code", + signedInAs: "octocat", + expiresLabel: "This request expires at 3:15:00 PM.", + decisionPath: "/agents/approve/7c9e6679-7425-40de-944b-e07fc1f90ae7", } const meta = { title: "Hub/Pages/Learnings/Agent connections", - component: AgentConnectionsPrototype, + component: AgentConnectionsPage, parameters: { layout: "fullscreen" }, args: { data: connections }, render: ({ data }) => data.view === "connections" ? ( - + ) : ( - + ), -} satisfies Meta +} satisfies Meta export default meta type Story = StoryObj @@ -81,26 +85,20 @@ export const NoConnectedAgents: Story = { args: { data: { ...connections, connections: [] } }, } export const RevokeConfirmation: Story = { - args: { data: connections }, play: async ({ canvas, userEvent }) => { await userEvent.click(canvas.getByRole("button", { name: "Revoke Visual Studio Code access" })) await canvas.findByRole("dialog", { name: "Revoke agent access?" }) }, } -export const ApprovalRequest: Story = { - args: { data: approval }, -} -export const Approved: Story = { - args: { data: approval }, - play: async ({ canvas, userEvent }) => { - await userEvent.click(canvas.getByRole("button", { name: "Approve access" })) - await canvas.findByRole("heading", { name: "Agent connected" }) +export const Revoked: Story = { + args: { + data: { + ...connections, + connections: connections.connections.slice(1), + notice: "Agent access revoked.", + }, }, } -export const Cancelled: Story = { +export const ApprovalRequest: Story = { args: { data: approval }, - play: async ({ canvas, userEvent }) => { - await userEvent.click(canvas.getByRole("button", { name: "Cancel" })) - await canvas.findByRole("heading", { name: "Connection cancelled" }) - }, } diff --git a/hub/client/pages/agent-connections-page/styles.css b/hub/client/pages/agent-connections-page/styles.css index 199e1f76..e368b569 100644 --- a/hub/client/pages/agent-connections-page/styles.css +++ b/hub/client/pages/agent-connections-page/styles.css @@ -14,16 +14,14 @@ .agent-connections__header, .agent-connections__section, -.agent-connections__approval, -.agent-connections__approval-result { +.agent-connections__approval { display: grid; gap: 0.75rem; } .agent-connections__header > p, .agent-connections__section > p, -.agent-connections__approval > p, -.agent-connections__approval-result > p { +.agent-connections__approval > p { color: var(--hub-fg-muted); } @@ -69,11 +67,6 @@ background: var(--hub-canvas-default); } -.agent-connections__approval-result { - max-width: 36rem; - margin: 10vh auto; -} - .agent-connections__actions { display: flex; flex-wrap: wrap; diff --git a/hub/client/pages/agent-connections-page/types.ts b/hub/client/pages/agent-connections-page/types.ts index 146d4bce..51687461 100644 --- a/hub/client/pages/agent-connections-page/types.ts +++ b/hub/client/pages/agent-connections-page/types.ts @@ -1,24 +1,24 @@ export interface AgentConnection { id: string name: string - connectedAt: string - lastUsedAt: string + connectedLabel: string + lastUsedLabel: string + revokePath: string } -interface AgentConnectionsPrototypeBase { - repositoryId: string - repositoryName: string - hubUrl: string - signedInAs: string -} - -export type AgentConnectionsPrototypeData = - | (AgentConnectionsPrototypeBase & { +export type AgentConnectionsPageData = + | { view: "connections" + repositoryName: string + mcpUrl: string + signedInAs: string connections: AgentConnection[] - }) - | (AgentConnectionsPrototypeBase & { + notice: string | null + } + | { view: "approval" - connections: AgentConnection[] requestingAgent: string - }) + signedInAs: string + expiresLabel: string + decisionPath: string + } diff --git a/hub/client/pages/learnings-page/index.tsx b/hub/client/pages/learnings-page/index.tsx index e02dca6f..7de3945d 100644 --- a/hub/client/pages/learnings-page/index.tsx +++ b/hub/client/pages/learnings-page/index.tsx @@ -81,14 +81,19 @@ function LearningsContent({ title={copy.heading} description={copy.description} trailing={ - data.run.available ? ( -
- - -
- ) : null +
+ + {data.run.available ? ( +
+ + +
+ ) : null} +
} /> {data.alert ? : null} diff --git a/hub/client/pages/learnings-page/stories.tsx b/hub/client/pages/learnings-page/stories.tsx index 85e54a8d..57558d9e 100644 --- a/hub/client/pages/learnings-page/stories.tsx +++ b/hub/client/pages/learnings-page/stories.tsx @@ -365,6 +365,7 @@ const data: LearningsPageData = { usage: "Copilot used 0.147 AI credits for this repository in the last 30 days.", }, run: { path: "/repositories/2001/learnings/runs", available: true }, + agentsPath: "/repositories/2001/learnings/agents", loadError: null, identityNotice: null, library, diff --git a/hub/client/pages/learnings-page/styles.css b/hub/client/pages/learnings-page/styles.css index dc042ba5..a57d95af 100644 --- a/hub/client/pages/learnings-page/styles.css +++ b/hub/client/pages/learnings-page/styles.css @@ -63,3 +63,9 @@ .learnings-page__run-state { font-weight: 600; } + +.learnings-page__header-actions { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; +} diff --git a/hub/client/pages/learnings-page/types.ts b/hub/client/pages/learnings-page/types.ts index 674221c0..d7b62a47 100644 --- a/hub/client/pages/learnings-page/types.ts +++ b/hub/client/pages/learnings-page/types.ts @@ -41,6 +41,7 @@ export type LearningsPageData = usage: string | null } run: { path: string; available: boolean } + agentsPath: string loadError: string | null identityNotice: string | null library: LearningsLibraryData From e95961ff256a12e7d678b45d88447d60047bbbd3 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 22:57:16 -0800 Subject: [PATCH 06/17] docs(hub): explain how to connect an agent to Hub Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25291e01-0146-42cb-ac6d-f5e1dd5c35f5 --- hub/docs/learning-foundation.md | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/hub/docs/learning-foundation.md b/hub/docs/learning-foundation.md index 6e433dbd..20ebb558 100644 --- a/hub/docs/learning-foundation.md +++ b/hub/docs/learning-foundation.md @@ -69,7 +69,7 @@ The address holds the whole library state, for example `/repositories/2001/learn Someone who administers both Hub and a repository can share one of that repository's active learnings with every repository in Hub by turning on "Share across Hub" on the learning. The switch saves right away. For example, sharing "Use one primary button per form" from `github/design-guidelines` adds the same guidance to the recall preview for `github/checkout`, and the `github/checkout` library lists it under Active as "Shared from github/design-guidelines". Members of a receiving repository can read a shared learning but cannot change it or see its review comments and history. Only the source repository can stop sharing it. -Agents in a receiving repository do not get shared learnings yet. The package accepts them only in a person's preview, because a delivered copy would be stored in the receiving repository and outlive the source's own deletion and audit. Delivering them to agents comes with Hub's hosted learning MCP server. +Agents in a receiving repository do not get shared learnings yet. The package accepts them only in a person's preview, because a delivered copy would be stored in the receiving repository and outlive the source's own deletion and audit. Hub's learning MCP server does not deliver them either. Hub checks that this repository's own agents get the learning before it records the share. Hub reads the source repository's store again each time it builds a receiving repository's recall, so edits, rejections, and stopped shares take effect on the next read. Hub reads up to four source stores at a time and gives each 10 seconds. A source store that cannot be read in time, or for any other reason, is skipped and logged so the receiving repository's own learnings still load. A shared learning whose ID matches one of the receiving repository's own learnings is hidden. A repository that has no learning store of its own yet shows no shared learnings. Rejecting or retiring a learning keeps its share saved, so it is shared again if the learning is accepted again. An administrator can stop the share from the rejected learning first. Stopping a share keeps its record, including who shared and who stopped sharing it, and both actions write security audits. @@ -107,6 +107,35 @@ The worker claims a queued run only once under the learning execution lock. It r Soft deletion queues an idempotent package redaction job after the review transaction commits. The recovery sweep also finds deleted review comments, and every later import uses `--redact-deleted`, so a transient queue failure cannot make a deleted body permanently eligible. +## Agent connections + +A coding agent can read a repository's learnings from Hub and report which ones it used. For example, someone working on `github/checkout` opens its Learnings page, chooses **Connect an agent**, and copies this into their agent's MCP settings: + +```json +{ "mcpServers": { "replica": { "url": "https://hub.example.com/mcp/repositories/" } } } +``` + +The configuration holds no credential. The first time the agent calls Hub, it gets a `401` that points to Hub's OAuth discovery document. An agent that supports [MCP authorization](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization) registers itself, opens `/agents/approve/:authorizationId` in the browser, and waits. The person signs in if needed and approves or cancels. Hub then sends the browser back to the agent with a one-time code, and the agent trades the code for tokens. + +The agent gets the same tools and instructions as `replica-learning mcp` in the [learning package](../../packages/learning/README.md#connect-an-agent), because Hub loads them from the installed package. Hub supplies the backend: + +- `get_guidance`, `list_learnings`, and `get_learning` read only the repository's own accepted instruction learnings. A proposed learning links to its Learnings page, where a person decides. +- `report_usage` records which learnings the agent applied. It refuses screenshots for now. +- `submit_session` is refused, because Hub does not collect agent sessions yet. + +Every request acts for the person who approved the connection. Hub rechecks their sign-in, membership, provider, and repository access each time, so ending the person's sessions or removing their access stops the agent too. A connection works for any repository the person can read, which is why the list is kept per person. People review and revoke their agents on the same page. Approving and revoking write security audits. + +Tokens use the same lifetimes as Canvas connections. An approval request expires after 10 minutes. Access tokens last seven days, refresh tokens rotate on use, and a connection unused for 30 days ends. Hub stores only digests of codes and tokens. Every agent is a public OAuth client that relies on PKCE, because agents run on people's machines and cannot keep a secret. + +The OAuth endpoints are `/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource/mcp`, `/register`, `/authorize`, `/token`, and `/revoke`. The browser endpoints are: + +- `GET /api/agent-connections/authorizations/:authorizationId` +- `POST /api/agent-connections/authorizations/:authorizationId/approve` and `/cancel` +- `GET /api/agent-connections` +- `DELETE /api/agent-connections/:connectionId` + +The MCP endpoint accepts `POST` only and needs `HUB_APPLICATION_ORIGIN` and the learning package. Local repositories are not supported, because learnings belong to GitHub repositories. + ## Configuration | Variable | Contract | From bcf84d7d50b48fdd3bbf78d01a7fcfdee902e846 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 23:08:10 -0800 Subject: [PATCH 07/17] fix(hub): keep server details out of agent error messages Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25291e01-0146-42cb-ac6d-f5e1dd5c35f5 --- .../create-learning-mcp-backend/index.test.ts | 38 +++++++++++++++++++ .../create-learning-mcp-backend/index.ts | 14 ++++++- 2 files changed, 50 insertions(+), 2 deletions(-) create mode 100644 hub/server/domains/agent-connections/create-learning-mcp-backend/index.test.ts diff --git a/hub/server/domains/agent-connections/create-learning-mcp-backend/index.test.ts b/hub/server/domains/agent-connections/create-learning-mcp-backend/index.test.ts new file mode 100644 index 00000000..d302bc07 --- /dev/null +++ b/hub/server/domains/agent-connections/create-learning-mcp-backend/index.test.ts @@ -0,0 +1,38 @@ +import { mkdtemp, realpath, rm } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { expect, it, onTestFinished, vi } from "vitest" + +import { LearningCommandError } from "../../../integrations/learning/run-learning-command/errors.ts" +import { createLearningMcpBackend } from "." + +const runLearningCommand = vi.hoisted(() => vi.fn()) +vi.mock("../../../integrations/learning/run-learning-command/index.ts", () => ({ + runLearningCommand, +})) + +it("keeps server details out of what agents see when the store fails", async () => { + const root = await realpath(await mkdtemp(join(tmpdir(), "replica-agent-backend-"))) + onTestFinished(() => rm(root, { recursive: true, force: true })) + runLearningCommand.mockRejectedValueOnce( + new LearningCommandError("storage_corrupt", `The store at ${root} is damaged.`), + ) + const backend = createLearningMcpBackend({ + connectionId: "connection", + learning: { + applicationRoot: join(root, "app"), + cliPath: "replica-learning", + learningDatabaseUrl: "postgresql://learning", + nodePath: process.execPath, + root: join(root, "learning"), + staticDirectories: [], + }, + learningsUrl: "https://hub.example/learnings", + repository: { id: "9f8f1d8e-4c1a-4a4b-8d43-6a9f6a6e7f10", githubRepositoryId: 1n }, + toAgentError: (code, message) => new Error(`${code}: ${message}`), + }) + + const failure = backend.listLearnings({}) + + await expect(failure).rejects.toBeInstanceOf(LearningCommandError) +}) diff --git a/hub/server/domains/agent-connections/create-learning-mcp-backend/index.ts b/hub/server/domains/agent-connections/create-learning-mcp-backend/index.ts index 20018d24..1b35a653 100644 --- a/hub/server/domains/agent-connections/create-learning-mcp-backend/index.ts +++ b/hub/server/domains/agent-connections/create-learning-mcp-backend/index.ts @@ -7,6 +7,14 @@ import { LearningCommandError } from "../../../integrations/learning/run-learnin import { validatePrivateStorageRoot } from "../../../utils/validate-private-storage-root/index.ts" import { learningStoreArguments } from "../../learning/learning-store-arguments/index.ts" +const agentErrorCodes = new Set([ + "conflict", + "invalid_input", + "invalid_transition", + "not_found", + "unsupported", +]) + interface LearningSettings { applicationRoot?: string cliPath: string @@ -80,8 +88,10 @@ export function createLearningMcpBackend(input: { }, ) } catch (error) { - // The command writes its messages for people, so agents may see them. - if (error instanceof LearningCommandError) throw toAgentError(error.code, error.message) + // These codes describe the agent's own request. Other failures can name server + // paths or storage, so they reach the agent only as a plain message. + if (error instanceof LearningCommandError && agentErrorCodes.has(error.code)) + throw toAgentError(error.code, error.message) throw error } } From af20648e9f312d6221558a2bb7d380d27610c374 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 23:32:09 -0800 Subject: [PATCH 08/17] refactor(hub): move the agent OAuth provider into its own module Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25291e01-0146-42cb-ac6d-f5e1dd5c35f5 --- .../mcp/agent-oauth-provider/index.ts | 84 +++++++++++++++ .../mcp/agent-oauth-provider/types.ts | 19 ++++ .../mcp/create-agent-auth-router/index.ts | 102 +----------------- .../mcp/require-agent-token/index.ts | 8 +- 4 files changed, 108 insertions(+), 105 deletions(-) create mode 100644 hub/server/integrations/mcp/agent-oauth-provider/index.ts create mode 100644 hub/server/integrations/mcp/agent-oauth-provider/types.ts diff --git a/hub/server/integrations/mcp/agent-oauth-provider/index.ts b/hub/server/integrations/mcp/agent-oauth-provider/index.ts new file mode 100644 index 00000000..7af308be --- /dev/null +++ b/hub/server/integrations/mcp/agent-oauth-provider/index.ts @@ -0,0 +1,84 @@ +import { + InvalidGrantError, + InvalidTokenError, +} from "@modelcontextprotocol/sdk/server/auth/errors.js" +import type { OAuthServerProvider } from "@modelcontextprotocol/sdk/server/auth/provider.js" + +import type { AgentOAuthService } from "./types.ts" + +function clientInformation(client: { id: string; name: string; redirectUris: string[] }) { + return { + client_id: client.id, + client_name: client.name, + redirect_uris: client.redirectUris, + grant_types: ["authorization_code", "refresh_token"], + response_types: ["code"], + token_endpoint_auth_method: "none", + } +} + +/** Adapts Hub's agent connections to the SDK's OAuth provider contract. */ +export function agentOAuthProvider(service: AgentOAuthService): OAuthServerProvider { + return { + clientsStore: { + getClient: async (id) => { + if (!/^[0-9a-f-]{36}$/i.test(id)) return undefined + const client = await service.getClient(id) + return client ? clientInformation(client) : undefined + }, + // Agents run on people's machines and cannot keep a secret, so every client is + // public and relies on PKCE. + registerClient: async (metadata) => { + const client = { + id: (metadata as { client_id?: string }).client_id ?? crypto.randomUUID(), + name: (metadata.client_name ?? "Coding agent").slice(0, 200), + redirectUris: metadata.redirect_uris.map(String), + } + await service.registerClient(client) + return { + ...clientInformation(client), + client_id_issued_at: Math.floor(Date.now() / 1000), + } + }, + }, + async authorize(client, params, response) { + const id = await service.startAuthorization({ + clientId: client.client_id, + redirectUri: params.redirectUri, + codeChallenge: params.codeChallenge, + ...(params.state === undefined ? {} : { state: params.state }), + }) + response.redirect(302, `/agents/approve/${id}`) + }, + async challengeForAuthorizationCode(client, code) { + const challenge = await service.challenge(client.client_id, code) + if (!challenge) throw new InvalidGrantError("The authorization code is invalid or expired.") + return challenge + }, + async exchangeAuthorizationCode(client, code, _verifier, redirectUri) { + const tokens = await service.exchangeCode(client.client_id, code, redirectUri) + if (!tokens) throw new InvalidGrantError("The authorization code is invalid or expired.") + return tokens + }, + async exchangeRefreshToken(client, refreshToken) { + const tokens = await service.refresh(client.client_id, refreshToken) + if (!tokens) throw new InvalidGrantError("The refresh token is invalid or expired.") + return tokens + }, + async verifyAccessToken(token) { + const result = await service.verify(token) + if (!result) throw new InvalidTokenError("The access token is invalid or expired.") + const { connection } = result + return { + token, + clientId: connection.clientId, + scopes: [], + expiresAt: Math.floor(connection.expiresAt.getTime() / 1000), + extra: { result }, + } + }, + async revokeToken(client, request) { + await service.revokeToken(client.client_id, request.token) + }, + } +} diff --git a/hub/server/integrations/mcp/agent-oauth-provider/types.ts b/hub/server/integrations/mcp/agent-oauth-provider/types.ts new file mode 100644 index 00000000..37bd0a6c --- /dev/null +++ b/hub/server/integrations/mcp/agent-oauth-provider/types.ts @@ -0,0 +1,19 @@ +import type { OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js" + +export interface AgentOAuthService { + registerClient(client: { id: string; name: string; redirectUris: string[] }): Promise + getClient(id: string): Promise<{ id: string; name: string; redirectUris: string[] } | null> + startAuthorization(input: { + clientId: string + redirectUri: string + codeChallenge: string + state?: string + }): Promise + challenge(clientId: string, code: string): Promise + exchangeCode(clientId: string, code: string, redirectUri?: string): Promise + refresh(clientId: string, refreshToken: string): Promise + verify(accessToken: string): Promise<{ + connection: { id: string; clientId: string; expiresAt: Date } + } | null> + revokeToken(clientId: string, token: string): Promise +} diff --git a/hub/server/integrations/mcp/create-agent-auth-router/index.ts b/hub/server/integrations/mcp/create-agent-auth-router/index.ts index 831e183a..d1320563 100644 --- a/hub/server/integrations/mcp/create-agent-auth-router/index.ts +++ b/hub/server/integrations/mcp/create-agent-auth-router/index.ts @@ -1,109 +1,11 @@ import type { RequestHandler } from "express" import { mcpAuthRouter } from "@modelcontextprotocol/sdk/server/auth/router.js" -import { - InvalidGrantError, - InvalidTokenError, -} from "@modelcontextprotocol/sdk/server/auth/errors.js" -import type { OAuthServerProvider } from "@modelcontextprotocol/sdk/server/auth/provider.js" -import type { OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js" -export interface AgentOAuthService { - registerClient(client: { id: string; name: string; redirectUris: string[] }): Promise - getClient(id: string): Promise<{ id: string; name: string; redirectUris: string[] } | null> - startAuthorization(input: { - clientId: string - redirectUri: string - codeChallenge: string - state?: string - }): Promise - challenge(clientId: string, code: string): Promise - exchangeCode(clientId: string, code: string, redirectUri?: string): Promise - refresh(clientId: string, refreshToken: string): Promise - verify(accessToken: string): Promise<{ - connection: { id: string; clientId: string; expiresAt: Date } - } | null> - revokeToken(clientId: string, token: string): Promise -} +import { agentOAuthProvider } from "../agent-oauth-provider/index.ts" +import type { AgentOAuthService } from "../agent-oauth-provider/types.ts" export const agentMcpPath = "/mcp" -function clientInformation(client: { id: string; name: string; redirectUris: string[] }) { - return { - client_id: client.id, - client_name: client.name, - redirect_uris: client.redirectUris, - grant_types: ["authorization_code", "refresh_token"], - response_types: ["code"], - token_endpoint_auth_method: "none", - } -} - -/** Adapts Hub's agent connections to the SDK's OAuth provider contract. */ -export function agentOAuthProvider(service: AgentOAuthService): OAuthServerProvider { - return { - clientsStore: { - getClient: async (id) => { - if (!/^[0-9a-f-]{36}$/i.test(id)) return undefined - const client = await service.getClient(id) - return client ? clientInformation(client) : undefined - }, - // Agents run on people's machines and cannot keep a secret, so every client is - // public and relies on PKCE. - registerClient: async (metadata) => { - const client = { - id: (metadata as { client_id?: string }).client_id ?? crypto.randomUUID(), - name: (metadata.client_name ?? "Coding agent").slice(0, 200), - redirectUris: metadata.redirect_uris.map(String), - } - await service.registerClient(client) - return { - ...clientInformation(client), - client_id_issued_at: Math.floor(Date.now() / 1000), - } - }, - }, - async authorize(client, params, response) { - const id = await service.startAuthorization({ - clientId: client.client_id, - redirectUri: params.redirectUri, - codeChallenge: params.codeChallenge, - ...(params.state === undefined ? {} : { state: params.state }), - }) - response.redirect(302, `/agents/approve/${id}`) - }, - async challengeForAuthorizationCode(client, code) { - const challenge = await service.challenge(client.client_id, code) - if (!challenge) throw new InvalidGrantError("The authorization code is invalid or expired.") - return challenge - }, - async exchangeAuthorizationCode(client, code, _verifier, redirectUri) { - const tokens = await service.exchangeCode(client.client_id, code, redirectUri) - if (!tokens) throw new InvalidGrantError("The authorization code is invalid or expired.") - return tokens - }, - async exchangeRefreshToken(client, refreshToken) { - const tokens = await service.refresh(client.client_id, refreshToken) - if (!tokens) throw new InvalidGrantError("The refresh token is invalid or expired.") - return tokens - }, - async verifyAccessToken(token) { - const result = await service.verify(token) - if (!result) throw new InvalidTokenError("The access token is invalid or expired.") - const { connection } = result - return { - token, - clientId: connection.clientId, - scopes: [], - expiresAt: Math.floor(connection.expiresAt.getTime() / 1000), - extra: { result }, - } - }, - async revokeToken(client, request) { - await service.revokeToken(client.client_id, request.token) - }, - } -} - /** * Serves OAuth discovery, client registration, sign-in and token endpoints, so agents * that support MCP authorization can connect with only Hub's MCP URL. diff --git a/hub/server/integrations/mcp/require-agent-token/index.ts b/hub/server/integrations/mcp/require-agent-token/index.ts index 49916f07..6480403a 100644 --- a/hub/server/integrations/mcp/require-agent-token/index.ts +++ b/hub/server/integrations/mcp/require-agent-token/index.ts @@ -2,11 +2,9 @@ import type { RequestHandler } from "express" import { requireBearerAuth } from "@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js" import { getOAuthProtectedResourceMetadataUrl } from "@modelcontextprotocol/sdk/server/auth/router.js" -import { - agentMcpPath, - agentOAuthProvider, - type AgentOAuthService, -} from "../create-agent-auth-router/index.ts" +import { agentOAuthProvider } from "../agent-oauth-provider/index.ts" +import type { AgentOAuthService } from "../agent-oauth-provider/types.ts" +import { agentMcpPath } from "../create-agent-auth-router/index.ts" /** * Rejects requests without a live agent token. The response points agents at Hub's OAuth From 06e85aa1b4c8c1c73834b6e7e50477abcbdad03d Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 23:32:09 -0800 Subject: [PATCH 09/17] fix(hub): log and proxy agent connection endpoints like other sign-in routes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25291e01-0146-42cb-ac6d-f5e1dd5c35f5 --- hub/server/create-app/index.ts | 8 ++++++++ hub/vite.config.ts | 12 ++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/hub/server/create-app/index.ts b/hub/server/create-app/index.ts index a679be7f..905e1a18 100644 --- a/hub/server/create-app/index.ts +++ b/hub/server/create-app/index.ts @@ -40,6 +40,14 @@ export function createApp({ "/api/auth", "/canvas/pair", "/agents/approve", + // Agent OAuth and MCP calls carry tokens, codes, and private tool arguments. + "/mcp", + "/.well-known/oauth-authorization-server", + "/.well-known/oauth-protected-resource", + "/register", + "/authorize", + "/token", + "/revoke", "/api/administrators", "/api/copilot-connection", "/api/session-revocation", diff --git a/hub/vite.config.ts b/hub/vite.config.ts index ed83c66c..48d51024 100644 --- a/hub/vite.config.ts +++ b/hub/vite.config.ts @@ -8,6 +8,14 @@ import { controlsValidatorPath, } from "./controls-validator-plugin.ts" +// Agents reach the MCP and OAuth endpoints at the root, so these go to Express too. +const hubProxy = { + "/api": { target: "http://127.0.0.1:3001", ws: true }, + "^/(?:mcp|register|authorize|token|revoke|\\.well-known/oauth-[a-z-]+)(?:/|$)": { + target: "http://127.0.0.1:3001", + }, +} + export default defineConfig({ plugins: [reactRouter(), controlsValidatorPlugin()], ssr: { @@ -20,12 +28,12 @@ export default defineConfig({ server: { port: 5173, strictPort: true, - proxy: { "/api": { target: "http://127.0.0.1:3001", ws: true } }, + proxy: hubProxy, }, preview: { port: 5173, strictPort: true, - proxy: { "/api": { target: "http://127.0.0.1:3001", ws: true } }, + proxy: hubProxy, }, resolve: { alias: { ...viteAliases, [controlsValidatorModule]: controlsValidatorPath } }, optimizeDeps: { include: [controlsValidatorModule] }, From 9ee22062c00b9efb5c29455536e4d4be6b2e0ece Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 23:32:09 -0800 Subject: [PATCH 10/17] fix(hub): run agent learning commands one at a time and recheck access Agent commands now share the learning execution lock, so they cannot overlap with each other or with Learnings page work. Each command confirms the connection still has repository access before its answer is returned. Private task text goes through a temporary file instead of the process list. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25291e01-0146-42cb-ac6d-f5e1dd5c35f5 --- .../create-learning-mcp-backend/index.test.ts | 120 +++++++++++++++++- .../create-learning-mcp-backend/index.ts | 100 +++++++++------ hub/server/index.ts | 1 + hub/server/routes/agent-connections/index.ts | 30 ++++- hub/server/routes/agent-connections/types.ts | 1 + 5 files changed, 213 insertions(+), 39 deletions(-) diff --git a/hub/server/domains/agent-connections/create-learning-mcp-backend/index.test.ts b/hub/server/domains/agent-connections/create-learning-mcp-backend/index.test.ts index d302bc07..696d3058 100644 --- a/hub/server/domains/agent-connections/create-learning-mcp-backend/index.test.ts +++ b/hub/server/domains/agent-connections/create-learning-mcp-backend/index.test.ts @@ -1,4 +1,4 @@ -import { mkdtemp, realpath, rm } from "node:fs/promises" +import { mkdtemp, readFile, realpath, rm } from "node:fs/promises" import { tmpdir } from "node:os" import { join } from "node:path" import { expect, it, onTestFinished, vi } from "vitest" @@ -18,6 +18,7 @@ it("keeps server details out of what agents see when the store fails", async () new LearningCommandError("storage_corrupt", `The store at ${root} is damaged.`), ) const backend = createLearningMcpBackend({ + confirmAccess: () => Promise.resolve(true), connectionId: "connection", learning: { applicationRoot: join(root, "app"), @@ -29,6 +30,7 @@ it("keeps server details out of what agents see when the store fails", async () }, learningsUrl: "https://hub.example/learnings", repository: { id: "9f8f1d8e-4c1a-4a4b-8d43-6a9f6a6e7f10", githubRepositoryId: 1n }, + serialize: (operation) => operation(new AbortController().signal), toAgentError: (code, message) => new Error(`${code}: ${message}`), }) @@ -36,3 +38,119 @@ it("keeps server details out of what agents see when the store fails", async () await expect(failure).rejects.toBeInstanceOf(LearningCommandError) }) + +it("passes the task through a private file and session values as data", async () => { + const root = await realpath(await mkdtemp(join(tmpdir(), "replica-agent-backend-"))) + onTestFinished(() => rm(root, { recursive: true, force: true })) + let task = "" + runLearningCommand.mockImplementationOnce(async (arguments_: string[]) => { + task = await readFile(arguments_[arguments_.indexOf("--task-file") + 1]!, "utf8") + return { guidanceId: "guidance", text: "Use tokens.", memories: [] } + }) + const backend = createLearningMcpBackend({ + confirmAccess: () => Promise.resolve(true), + connectionId: "connection", + learning: { + applicationRoot: join(root, "app"), + cliPath: "replica-learning", + learningDatabaseUrl: "postgresql://learning", + nodePath: process.execPath, + root: join(root, "learning"), + staticDirectories: [], + }, + learningsUrl: "https://hub.example/learnings", + repository: { id: "9f8f1d8e-4c1a-4a4b-8d43-6a9f6a6e7f10", githubRepositoryId: 1n }, + serialize: (operation) => operation(new AbortController().signal), + toAgentError: (code, message) => new Error(`${code}: ${message}`), + }) + + await backend.getGuidance({ task: "-private task", session: { id: "-s", label: "-l" } }) + + const arguments_ = runLearningCommand.mock.calls.at(-1)![0] as string[] + expect(task).toBe("-private task") + expect(arguments_).not.toContain("-private task") + expect(arguments_).toEqual(expect.arrayContaining(["--session-id=-s", "--session-label=-l"])) +}) + +it("withholds guidance when the connection loses access while the command runs", async () => { + const root = await realpath(await mkdtemp(join(tmpdir(), "replica-agent-backend-"))) + onTestFinished(() => rm(root, { recursive: true, force: true })) + runLearningCommand.mockResolvedValueOnce({ guidanceId: "g", text: "Secret.", memories: [] }) + const backend = createLearningMcpBackend({ + confirmAccess: () => Promise.resolve(false), + connectionId: "connection", + learning: { + applicationRoot: join(root, "app"), + cliPath: "replica-learning", + learningDatabaseUrl: "postgresql://learning", + nodePath: process.execPath, + root: join(root, "learning"), + staticDirectories: [], + }, + learningsUrl: "https://hub.example/learnings", + repository: { id: "9f8f1d8e-4c1a-4a4b-8d43-6a9f6a6e7f10", githubRepositoryId: 1n }, + serialize: (operation) => operation(new AbortController().signal), + toAgentError: (code, message) => new Error(`${code}: ${message}`), + }) + + const guidance = backend.getGuidance({}) + + await expect(guidance).rejects.toThrow("access_denied") +}) + +it("withholds the text of a learning no one has accepted", async () => { + const root = await realpath(await mkdtemp(join(tmpdir(), "replica-agent-backend-"))) + onTestFinished(() => rm(root, { recursive: true, force: true })) + runLearningCommand.mockResolvedValueOnce({ + record: { id: "memory-1", state: "proposed", text: "Unreviewed idea." }, + status: { recallEligible: false }, + withheld: false, + }) + const backend = createLearningMcpBackend({ + confirmAccess: () => Promise.resolve(true), + connectionId: "connection", + learning: { + applicationRoot: join(root, "app"), + cliPath: "replica-learning", + learningDatabaseUrl: "postgresql://learning", + nodePath: process.execPath, + root: join(root, "learning"), + staticDirectories: [], + }, + learningsUrl: "https://hub.example/learnings", + repository: { id: "9f8f1d8e-4c1a-4a4b-8d43-6a9f6a6e7f10", githubRepositoryId: 1n }, + serialize: (operation) => operation(new AbortController().signal), + toAgentError: (code, message) => new Error(`${code}: ${message}`), + }) + + const learning = await backend.getLearning({ id: "memory-1" }) + + expect(JSON.stringify(learning)).not.toContain("Unreviewed idea.") + expect(learning).toMatchObject({ id: "memory-1", state: "proposed", withheld: true }) +}) + +it("gives no guidance for a repository without a learning store", async () => { + const root = await realpath(await mkdtemp(join(tmpdir(), "replica-agent-backend-"))) + onTestFinished(() => rm(root, { recursive: true, force: true })) + runLearningCommand.mockClear() + const backend = createLearningMcpBackend({ + confirmAccess: () => Promise.resolve(true), + connectionId: "connection", + learning: { + applicationRoot: join(root, "app"), + cliPath: "replica-learning", + nodePath: process.execPath, + root: join(root, "learning"), + staticDirectories: [], + }, + learningsUrl: "https://hub.example/learnings", + repository: { id: "9f8f1d8e-4c1a-4a4b-8d43-6a9f6a6e7f10", githubRepositoryId: 1n }, + serialize: (operation) => operation(new AbortController().signal), + toAgentError: (code, message) => new Error(`${code}: ${message}`), + }) + + const guidance = await backend.getGuidance({ task: "Build a form" }) + + expect(guidance).toEqual({ guidanceId: null, text: "", learnings: [] }) + expect(runLearningCommand).not.toHaveBeenCalled() +}) diff --git a/hub/server/domains/agent-connections/create-learning-mcp-backend/index.ts b/hub/server/domains/agent-connections/create-learning-mcp-backend/index.ts index 1b35a653..193ead61 100644 --- a/hub/server/domains/agent-connections/create-learning-mcp-backend/index.ts +++ b/hub/server/domains/agent-connections/create-learning-mcp-backend/index.ts @@ -30,16 +30,30 @@ interface StoredLearning { withheld: boolean } +/** Writes private text to a file only this process can read, and removes it afterwards. */ +async function withPrivateFile(content: string, operation: (file: string) => Promise) { + const folder = await mkdtemp(join(tmpdir(), "replica-agent-")) + try { + const file = join(folder, "input") + await writeFile(file, content, { mode: 0o600 }) + return await operation(file) + } finally { + await rm(folder, { recursive: true, force: true }) + } +} + /** * Answers one agent's learning tools for one repository by running the replica-learning * command, the same way the Learnings page does. Each call names the connection as the * agent, so records show which connection received or used guidance. */ export function createLearningMcpBackend(input: { + confirmAccess(): Promise connectionId: string learning: LearningSettings learningsUrl: string repository: { id: string; githubRepositoryId: bigint } + serialize(operation: (signal: AbortSignal) => Promise): Promise toAgentError: (code: string, message: string) => Error }) { const { learning, repository, toAgentError } = input @@ -66,27 +80,37 @@ export function createLearningMcpBackend(input: { } } + /** + * Runs one command while no other learning work can change the store, then checks the + * connection still has access, so a revoked agent never receives what it asked for. + */ async function run(directory: string, arguments_: string[]) { try { - return await runLearningCommand( - [ - ...arguments_, - "--actor", - actor, - ...learningStoreArguments({ - directory, - repositoryId: repository.id, - repositoryScope: `github.com/repositories/${repository.githubRepositoryId}`, - }), - ], - { - cliPath: learning.cliPath, - nodePath: learning.nodePath, - ...(learning.learningDatabaseUrl - ? { learningDatabaseUrl: learning.learningDatabaseUrl } - : {}), - }, - ) + return await input.serialize(async (signal) => { + const result = await runLearningCommand( + [ + ...arguments_, + "--actor", + actor, + ...learningStoreArguments({ + directory, + repositoryId: repository.id, + repositoryScope: `github.com/repositories/${repository.githubRepositoryId}`, + }), + ], + { + cliPath: learning.cliPath, + nodePath: learning.nodePath, + signal, + ...(learning.learningDatabaseUrl + ? { learningDatabaseUrl: learning.learningDatabaseUrl } + : {}), + }, + ) + if (!(await input.confirmAccess())) + throw toAgentError("access_denied", "This agent connection no longer has access.") + return result + }) } catch (error) { // These codes describe the agent's own request. Other failures can name server // paths or storage, so they reach the agent only as a plain message. @@ -98,10 +122,10 @@ export function createLearningMcpBackend(input: { function sessionArguments(session?: { id: string; label?: string }) { if (!session) return [] + // Joined to the flag so a value starting with "-" is read as data. return [ - "--session-id", - session.id, - ...(session.label === undefined ? [] : ["--session-label", session.label]), + `--session-id=${session.id}`, + ...(session.label === undefined ? [] : [`--session-label=${session.label}`]), ] } @@ -117,13 +141,20 @@ export function createLearningMcpBackend(input: { }) { const directory = await storeDirectory() if (!directory) return { guidanceId: null, text: "", learnings: [] } - const result = (await run(directory, [ - "recall", - ...(task === undefined ? [] : ["--task", task]), - "--limit", - String(limit ?? 20), - ...sessionArguments(session), - ])) as { + const store = directory + function recall(taskArguments: string[]) { + return run(store, [ + "recall", + ...taskArguments, + "--limit", + String(limit ?? 20), + ...sessionArguments(session), + ]) + } + // The task goes through a private file so it never shows in the process list. + const result = (await (task === undefined + ? recall([]) + : withPrivateFile(task, (file) => recall(["--task-file", file])))) as { guidanceId: string text: string memories: { id: string; deliveryId: string }[] @@ -145,14 +176,9 @@ export function createLearningMcpBackend(input: { const directory = await storeDirectory() if (!directory) throw toAgentError("not_found", "This repository has no learnings to report on.") - const folder = await mkdtemp(join(tmpdir(), "replica-agent-report-")) - try { - const file = join(folder, "report.json") - await writeFile(file, JSON.stringify(report), { mode: 0o600 }) - return await run(directory, ["report-usage", file]) - } finally { - await rm(folder, { recursive: true, force: true }) - } + return withPrivateFile(JSON.stringify(report), (file) => + run(directory, ["report-usage", file]), + ) }, submitSession() { diff --git a/hub/server/index.ts b/hub/server/index.ts index cc079e2f..7b18b125 100644 --- a/hub/server/index.ts +++ b/hub/server/index.ts @@ -190,6 +190,7 @@ try { if (learningConfiguration && agentApplicationOrigin) { agentConnections = { applicationOrigin: agentApplicationOrigin, + databaseUrl, learning: learningConfiguration, } } diff --git a/hub/server/routes/agent-connections/index.ts b/hub/server/routes/agent-connections/index.ts index f9b4475a..8c3a8a9e 100644 --- a/hub/server/routes/agent-connections/index.ts +++ b/hub/server/routes/agent-connections/index.ts @@ -18,6 +18,7 @@ import { loadLearningMcp } from "../../integrations/learning/load-learning-mcp/i import { createAgentAuthRouter } from "../../integrations/mcp/create-agent-auth-router/index.ts" import { handleMcpRequest } from "../../integrations/mcp/handle-mcp-request/index.ts" import { requireAgentToken } from "../../integrations/mcp/require-agent-token/index.ts" +import { withLearningExecutionLock } from "../../integrations/postgres/with-learning-execution-lock/index.ts" import { findAgentRepository } from "../../repositories/agent-connections/find-agent-repository/index.ts" import type { AgentConnectionRouteDependencies } from "./types.ts" @@ -37,7 +38,7 @@ export function agentConnectionRoutes( getRepositoryPermission?: GetCanvasRepositoryPermission, logger?: Logger, ) { - const { applicationOrigin, learning } = dependencies + const { applicationOrigin, databaseUrl, learning } = dependencies const router = express.Router() const browserMutation = requireOrigin(applicationOrigin) @@ -179,11 +180,38 @@ export function agentConnectionRoutes( if ((await authority.permission(result.viewer, repository)) === "none") return status(response, 403, "Repository access was denied.") const mcp = await loadLearningMcp(learning.cliPath) + const token = request.auth!.token const backend = createLearningMcpBackend({ + async confirmAccess() { + const current = await (await load()).connections.verify(token) + const stillListed = current && (await findAgentRepository(prisma, repository.id)) + return Boolean( + stillListed && (await authority.permission(current.viewer, stillListed)) !== "none", + ) + }, connectionId: result.connection.id, learning, learningsUrl: new URL(`/repositories/${repository.id}/learnings`, applicationOrigin).href, repository: { id: repository.id, githubRepositoryId: repository.githubRepositoryId }, + async serialize(operation) { + try { + return await withLearningExecutionLock({ + databaseUrl, + protectSessionAuthority: true, + run: operation, + }) + } catch (error) { + if ( + error instanceof Error && + error.message === "Another learning operation is still running." + ) + throw new mcp.LearningError( + "busy", + "Hub is busy with other learning work. Try again in a minute.", + ) + throw error + } + }, toAgentError: (code, message) => new mcp.LearningError(code, message), }) const server = mcp.createLearningMcpServer(backend, { diff --git a/hub/server/routes/agent-connections/types.ts b/hub/server/routes/agent-connections/types.ts index 2c99be9e..31576597 100644 --- a/hub/server/routes/agent-connections/types.ts +++ b/hub/server/routes/agent-connections/types.ts @@ -1,5 +1,6 @@ export interface AgentConnectionRouteDependencies { applicationOrigin: string + databaseUrl: string learning: { cliPath: string learningDatabaseUrl?: string From 9051c343ac21a0db986035dc748bc6cf9295616e Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 23:32:09 -0800 Subject: [PATCH 11/17] fix(hub): tie agent approval to the shown account and show where access goes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25291e01-0146-42cb-ac6d-f5e1dd5c35f5 --- .../application/hub/agent-connections/contract.ts | 8 +++++++- .../application/hub/routes/agent-approval/index.tsx | 13 +++++++++++-- hub/client/pages/agent-connections-page/index.tsx | 12 ++++++++++++ hub/client/pages/agent-connections-page/stories.tsx | 6 ++++++ hub/client/pages/agent-connections-page/types.ts | 5 +++++ .../create-agent-connections/index.ts | 8 +++++++- hub/server/routes/agent-connections/index.ts | 7 +++++++ 7 files changed, 55 insertions(+), 4 deletions(-) diff --git a/hub/client/application/hub/agent-connections/contract.ts b/hub/client/application/hub/agent-connections/contract.ts index b9f0ef32..02492293 100644 --- a/hub/client/application/hub/agent-connections/contract.ts +++ b/hub/client/application/hub/agent-connections/contract.ts @@ -1,7 +1,13 @@ import { z } from "zod" export const agentAuthorizationSchema = z - .object({ agent: z.string().min(1), signedInAs: z.string().min(1), expiresAt: z.iso.datetime() }) + .object({ + agent: z.string().min(1), + redirectUri: z.url(), + session: z.string().min(1).max(255), + signedInAs: z.string().min(1), + expiresAt: z.iso.datetime(), + }) .strict() export const agentDecisionSchema = z.object({ redirectUrl: z.url() }).strict() diff --git a/hub/client/application/hub/routes/agent-approval/index.tsx b/hub/client/application/hub/routes/agent-approval/index.tsx index 998a37be..9609fd99 100644 --- a/hub/client/application/hub/routes/agent-approval/index.tsx +++ b/hub/client/application/hub/routes/agent-approval/index.tsx @@ -29,9 +29,13 @@ export async function clientLoader({ request, params }: Route.ClientLoaderArgs) agentAuthorizationSchema, { signal: request.signal }, ) + const destination = new URL(authorization.redirectUri) const page: AgentConnectionsPageData = { view: "approval", requestingAgent: authorization.agent, + destination: destination.host, + localDestination: ["localhost", "127.0.0.1", "[::1]"].includes(destination.hostname), + session: authorization.session, signedInAs: authorization.signedInAs, expiresLabel: `This request expires at ${new Date(authorization.expiresAt).toLocaleTimeString()}.`, decisionPath: browserPath, @@ -48,14 +52,19 @@ export async function clientLoader({ request, params }: Route.ClientLoaderArgs) export async function clientAction({ request, params }: Route.ClientActionArgs) { const { id, browserPath } = authorizationPath(params.authorizationId) if (request.method !== "POST") throw new Response("Method not allowed.", { status: 405 }) - const decision = (await request.formData()).get("decision") + const form = await request.formData() + const decision = form.get("decision") if (decision !== "approve" && decision !== "cancel") throw new Response("Choose whether to approve this agent.", { status: 422 }) try { const { redirectUrl } = await requestJson( new URL(`/api/agent-connections/authorizations/${id}/${decision}`, request.url), agentDecisionSchema, - { method: "POST", signal: request.signal }, + { + method: "POST", + body: JSON.stringify({ session: form.get("session") }), + signal: request.signal, + }, ) // The agent listens on its own address, so the browser leaves Hub to finish. return redirect(redirectUrl) diff --git a/hub/client/pages/agent-connections-page/index.tsx b/hub/client/pages/agent-connections-page/index.tsx index 72e93aae..d557590c 100644 --- a/hub/client/pages/agent-connections-page/index.tsx +++ b/hub/client/pages/agent-connections-page/index.tsx @@ -3,6 +3,7 @@ import { Button, Heading, Text } from "@primer/react-brand" import { CanvasDialog } from "@components/prototype-canvas-dialog" import { CopyableCodeBlock } from "@components/copyable-code-block" +import { HubAlert } from "@components/hub-alert" import { HubToast } from "@components/hub-toast" import type { AgentConnectionsPageData } from "./types" @@ -29,6 +30,16 @@ export function AgentConnectionsPage({ Connect {data.requestingAgent} to Hub? + + Hub cannot confirm this agent's name. Approving sends access to{" "} + {data.destination}. + + {data.localDestination ? null : ( + + )} You are signed in as @{data.signedInAs}. This agent can read guidance and report which learnings it applied for repositories you can access. Hub checks access @@ -40,6 +51,7 @@ export function AgentConnectionsPage({ {data.expiresLabel}
+ diff --git a/hub/client/pages/agent-connections-page/stories.tsx b/hub/client/pages/agent-connections-page/stories.tsx index d940e1d5..91c65774 100644 --- a/hub/client/pages/agent-connections-page/stories.tsx +++ b/hub/client/pages/agent-connections-page/stories.tsx @@ -57,6 +57,9 @@ const connections: AgentConnectionsPageData = { const approval: AgentConnectionsPageData = { view: "approval", requestingAgent: "Visual Studio Code", + destination: "127.0.0.1:33418", + localDestination: true, + session: "session-octocat", signedInAs: "octocat", expiresLabel: "This request expires at 3:15:00 PM.", decisionPath: "/agents/approve/7c9e6679-7425-40de-944b-e07fc1f90ae7", @@ -102,3 +105,6 @@ export const Revoked: Story = { export const ApprovalRequest: Story = { args: { data: approval }, } +export const RemoteApprovalRequest: Story = { + args: { data: { ...approval, destination: "agent.example.net", localDestination: false } }, +} diff --git a/hub/client/pages/agent-connections-page/types.ts b/hub/client/pages/agent-connections-page/types.ts index 51687461..21d17301 100644 --- a/hub/client/pages/agent-connections-page/types.ts +++ b/hub/client/pages/agent-connections-page/types.ts @@ -18,6 +18,11 @@ export type AgentConnectionsPageData = | { view: "approval" requestingAgent: string + /** Where the agent asked Hub to send its access, such as "127.0.0.1:33418". */ + destination: string + /** Whether that address is on the person's own computer. */ + localDestination: boolean + session: string signedInAs: string expiresLabel: string decisionPath: string diff --git a/hub/server/domains/agent-connections/create-agent-connections/index.ts b/hub/server/domains/agent-connections/create-agent-connections/index.ts index 533218b7..33baf3a2 100644 --- a/hub/server/domains/agent-connections/create-agent-connections/index.ts +++ b/hub/server/domains/agent-connections/create-agent-connections/index.ts @@ -82,7 +82,13 @@ export function createAgentConnections(database: PrismaClient) { async readAuthorization(id: string) { const pending = await findPendingAgentAuthorization(database, id) - return pending && { clientName: pending.client.name, expiresAt: pending.expiresAt } + return ( + pending && { + clientName: pending.client.name, + expiresAt: pending.expiresAt, + redirectUri: pending.redirectUri, + } + ) }, async decideAuthorization(id: string, browser: CanvasBrowser, approve: boolean) { diff --git a/hub/server/routes/agent-connections/index.ts b/hub/server/routes/agent-connections/index.ts index 8c3a8a9e..9b622abb 100644 --- a/hub/server/routes/agent-connections/index.ts +++ b/hub/server/routes/agent-connections/index.ts @@ -95,6 +95,11 @@ export function agentConnectionRoutes( const id = String(request.params.authorizationId) const session = await browser(request) if (!session) return status(response, 401, "Sign in to continue.") + // The page names the account it loaded with. If another tab switched accounts since, + // the person has not seen who they would be granting access as. + const shown = (request.body as { session?: unknown } | undefined)?.session + if (shown !== session.sessionId) + return status(response, 409, "You switched accounts. Review this request again.") const redirectUrl = uuidPattern.test(id) ? await (await load()).connections.decideAuthorization(id, session, approve) : null @@ -119,6 +124,8 @@ export function agentConnectionRoutes( return status(response, 410, "This request expired. Connect again from your agent.") response.json({ agent: pending.clientName, + redirectUri: pending.redirectUri, + session: session.sessionId, signedInAs: session.viewer.login, expiresAt: pending.expiresAt.toISOString(), }) From 21e28108ed0be919229b0e572df3cbfe68d4e45b Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 23:32:17 -0800 Subject: [PATCH 12/17] fix(hub): keep agent page stories from submitting their forms Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25291e01-0146-42cb-ac6d-f5e1dd5c35f5 --- .../pages/agent-connections-page/stories.tsx | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/hub/client/pages/agent-connections-page/stories.tsx b/hub/client/pages/agent-connections-page/stories.tsx index 91c65774..3b587f21 100644 --- a/hub/client/pages/agent-connections-page/stories.tsx +++ b/hub/client/pages/agent-connections-page/stories.tsx @@ -70,14 +70,18 @@ const meta = { component: AgentConnectionsPage, parameters: { layout: "fullscreen" }, args: { data: connections }, - render: ({ data }) => - data.view === "connections" ? ( - + // The page's forms post to Hub, so stories keep them from leaving Storybook. + render: ({ data }) => ( +
event.preventDefault()}> + {data.view === "connections" ? ( + + + + ) : ( - - ) : ( - - ), + )} +
+ ), } satisfies Meta export default meta From 111cb5534b2dde8657fa51e586c90b39186090f3 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 23:32:17 -0800 Subject: [PATCH 13/17] fix(hub): audit agent revocations and list only usable connections Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25291e01-0146-42cb-ac6d-f5e1dd5c35f5 --- .../create-agent-connections/index.ts | 28 ++++++++++++++----- .../find-pending-agent-authorization/index.ts | 1 + .../list-agent-connections/index.ts | 3 +- .../record-agent-connection-audit/index.ts | 22 +++++++-------- .../present-security-audit/index.ts | 4 +++ 5 files changed, 38 insertions(+), 20 deletions(-) diff --git a/hub/server/domains/agent-connections/create-agent-connections/index.ts b/hub/server/domains/agent-connections/create-agent-connections/index.ts index 33baf3a2..458255bb 100644 --- a/hub/server/domains/agent-connections/create-agent-connections/index.ts +++ b/hub/server/domains/agent-connections/create-agent-connections/index.ts @@ -106,7 +106,7 @@ export function createAgentConnections(database: PrismaClient) { await recordAgentConnectionAudit(transaction, { action: "agent_connection.approve", actorMembershipId: browser.viewer.membershipId, - authorizationId: id, + clientId: pending.clientId, }) } return settled @@ -184,15 +184,29 @@ export function createAgentConnections(database: PrismaClient) { }, async revokeToken(clientId: string, token: string) { - if (accessPattern.test(token)) - await revokeAgentConnection(database, { clientId, tokenDigest: canvasDigest(token) }) - else if (refreshPattern.test(token)) - await revokeAgentConnection(database, { clientId, refreshDigest: canvasDigest(token) }) + const digest = canvasDigest(token) + const where = accessPattern.test(token) + ? { clientId, tokenDigest: digest } + : refreshPattern.test(token) + ? { clientId, refreshDigest: digest } + : null + if (!where) return + await database.$transaction(async (transaction) => { + const revoked = await revokeAgentConnection(transaction, where) + if (!revoked) return + await recordAgentConnectionAudit(transaction, { + action: "agent_connection.revoke", + actorMembershipId: revoked.membershipId, + connectionId: revoked.id, + }) + }) }, + // Only connections that would still pass verify() are listed, so ones ended by a + // sign-out everywhere or a provider change do not look connected. list(browser: CanvasBrowser) { - const { membershipId, externalIdentityId } = browser.viewer - return listAgentConnections(database, { membershipId, externalIdentityId }) + const reference = canvasAuthorityReference(browser.viewer) + return reference ? listAgentConnections(database, reference) : Promise.resolve([]) }, revokeBrowser(id: string, browser: CanvasBrowser) { diff --git a/hub/server/repositories/agent-authorizations/find-pending-agent-authorization/index.ts b/hub/server/repositories/agent-authorizations/find-pending-agent-authorization/index.ts index 2e4d0ade..01e0f9a4 100644 --- a/hub/server/repositories/agent-authorizations/find-pending-agent-authorization/index.ts +++ b/hub/server/repositories/agent-authorizations/find-pending-agent-authorization/index.ts @@ -8,6 +8,7 @@ export function findPendingAgentAuthorization( where: { id, expiresAt: { gt: new Date() }, approvedAt: null, consumedAt: null }, select: { id: true, + clientId: true, redirectUri: true, state: true, expiresAt: true, diff --git a/hub/server/repositories/agent-connections/list-agent-connections/index.ts b/hub/server/repositories/agent-connections/list-agent-connections/index.ts index ebef9297..8c55133b 100644 --- a/hub/server/repositories/agent-connections/list-agent-connections/index.ts +++ b/hub/server/repositories/agent-connections/list-agent-connections/index.ts @@ -1,8 +1,9 @@ import type { Prisma } from "../../../generated/prisma/client.ts" +import type { CanvasAuthorityReference } from "../../canvas/authority/index.ts" export function listAgentConnections( database: Pick, - owner: { membershipId: string; externalIdentityId: string }, + owner: CanvasAuthorityReference, ) { const now = new Date() return database.agentConnection.findMany({ diff --git a/hub/server/repositories/agent-connections/record-agent-connection-audit/index.ts b/hub/server/repositories/agent-connections/record-agent-connection-audit/index.ts index 0a730ef5..848f9d9e 100644 --- a/hub/server/repositories/agent-connections/record-agent-connection-audit/index.ts +++ b/hub/server/repositories/agent-connections/record-agent-connection-audit/index.ts @@ -5,22 +5,20 @@ export function recordAgentConnectionAudit( input: { action: "agent_connection.approve" | "agent_connection.revoke" actorMembershipId: string - connectionId?: string - authorizationId?: string - }, + } & ({ connectionId: string } | { clientId: string }), ) { - const { action, actorMembershipId, connectionId, authorizationId } = input + // An approval happens before its connection exists, so it names the lasting agent + // client instead of the short-lived authorization request. + const target = + "connectionId" in input + ? { targetType: "agent_connection", targetId: input.connectionId } + : { targetType: "agent_client", targetId: input.clientId } return database.securityAudit.create({ data: { - action, + action: input.action, outcome: "SUCCESS", - targetType: connectionId ? "agent_connection" : "agent_authorization", - targetId: connectionId ?? authorizationId ?? null, - context: { - actorMembershipId, - ...(connectionId ? { connectionId } : {}), - ...(authorizationId ? { authorizationId } : {}), - }, + ...target, + context: { actorMembershipId: input.actorMembershipId }, }, }) } diff --git a/hub/server/routes/api/security-audits/present-security-audit/index.ts b/hub/server/routes/api/security-audits/present-security-audit/index.ts index 8d14f63b..7efb061b 100644 --- a/hub/server/routes/api/security-audits/present-security-audit/index.ts +++ b/hub/server/routes/api/security-audits/present-security-audit/index.ts @@ -501,6 +501,10 @@ function contextFor(record: SecurityAuditListRecord): Record Date: Wed, 25 Nov 2026 23:32:17 -0800 Subject: [PATCH 14/17] fix(hub): hide agent setup for local repositories Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25291e01-0146-42cb-ac6d-f5e1dd5c35f5 --- .../hub/routes/learning-agents/index.tsx | 2 +- .../view-models/settings-learnings/index.ts | 5 ++++- .../pages/agent-connections-page/index.tsx | 22 +++++++++++++------ .../pages/agent-connections-page/stories.tsx | 3 +++ .../pages/agent-connections-page/types.ts | 3 ++- hub/client/pages/learnings-page/index.tsx | 8 ++++--- hub/client/pages/learnings-page/types.ts | 2 +- 7 files changed, 31 insertions(+), 14 deletions(-) diff --git a/hub/client/application/hub/routes/learning-agents/index.tsx b/hub/client/application/hub/routes/learning-agents/index.tsx index e19333e1..b5bf475b 100644 --- a/hub/client/application/hub/routes/learning-agents/index.tsx +++ b/hub/client/application/hub/routes/learning-agents/index.tsx @@ -92,7 +92,7 @@ export default function LearningAgents({ loaderData, params }: Route.ComponentPr data={{ view: "connections", repositoryName: repository?.nameWithOwner ?? "this repository", - mcpUrl: loaderData.mcpUrl, + mcpUrl: repository?.capabilities?.local ? null : loaderData.mcpUrl, signedInAs: workspace?.viewer.login ?? "", connections: loaderData.connections, notice: busy ? null : (fetcher.data?.notice ?? null), diff --git a/hub/client/application/hub/view-models/settings-learnings/index.ts b/hub/client/application/hub/view-models/settings-learnings/index.ts index 45bf18c4..00cf3739 100644 --- a/hub/client/application/hub/view-models/settings-learnings/index.ts +++ b/hub/client/application/hub/view-models/settings-learnings/index.ts @@ -334,7 +334,10 @@ export function settingsLearnings( ? null : `Copilot used ${formatCredits(state.usageCredits)} for this repository in the last 30 days.`, }, - agentsPath: `/repositories/${repositoryId}/learnings/agents`, + // Hub serves agents only for GitHub repositories, so local ones offer no setup. + agentsPath: workspace.repositories.find(({ id }) => id === repositoryId)?.capabilities?.local + ? null + : `/repositories/${repositoryId}/learnings/agents`, run: { path: `/repositories/${repositoryId}/learnings/runs`, available: state.permissions.requestRun && state.runAvailable, diff --git a/hub/client/pages/agent-connections-page/index.tsx b/hub/client/pages/agent-connections-page/index.tsx index d557590c..7ea8423f 100644 --- a/hub/client/pages/agent-connections-page/index.tsx +++ b/hub/client/pages/agent-connections-page/index.tsx @@ -64,7 +64,6 @@ export function AgentConnectionsPage({ ) } - const configuration = JSON.stringify({ mcpServers: { replica: { url: data.mcpUrl } } }, null, 2) const selectedConnection = data.connections.find(({ id }) => id === connectionToRevoke) return ( @@ -82,12 +81,21 @@ export function AgentConnectionsPage({ Add Hub to your agent - - Copy this configuration into your agent. It contains the Hub address for this repository, - not a password or access token. Your agent will open a browser when it needs you to sign - in. - - + {data.mcpUrl ? ( + <> + + Copy this configuration into your agent. It contains the Hub address for this + repository, not a password or access token. Your agent will open a browser when it + needs you to sign in. + + + + ) : ( + Hub can connect agents only to GitHub repositories. + )}
diff --git a/hub/client/pages/agent-connections-page/stories.tsx b/hub/client/pages/agent-connections-page/stories.tsx index 3b587f21..4cac93c4 100644 --- a/hub/client/pages/agent-connections-page/stories.tsx +++ b/hub/client/pages/agent-connections-page/stories.tsx @@ -91,6 +91,9 @@ export const ConnectedAgents: Story = {} export const NoConnectedAgents: Story = { args: { data: { ...connections, connections: [] } }, } +export const LocalRepository: Story = { + args: { data: { ...connections, mcpUrl: null } }, +} export const RevokeConfirmation: Story = { play: async ({ canvas, userEvent }) => { await userEvent.click(canvas.getByRole("button", { name: "Revoke Visual Studio Code access" })) diff --git a/hub/client/pages/agent-connections-page/types.ts b/hub/client/pages/agent-connections-page/types.ts index 21d17301..6b66d8ba 100644 --- a/hub/client/pages/agent-connections-page/types.ts +++ b/hub/client/pages/agent-connections-page/types.ts @@ -10,7 +10,8 @@ export type AgentConnectionsPageData = | { view: "connections" repositoryName: string - mcpUrl: string + /** Null for a repository Hub cannot serve to agents, such as a local one. */ + mcpUrl: string | null signedInAs: string connections: AgentConnection[] notice: string | null diff --git a/hub/client/pages/learnings-page/index.tsx b/hub/client/pages/learnings-page/index.tsx index 7de3945d..1a34e650 100644 --- a/hub/client/pages/learnings-page/index.tsx +++ b/hub/client/pages/learnings-page/index.tsx @@ -82,9 +82,11 @@ function LearningsContent({ description={copy.description} trailing={
- + {data.agentsPath ? ( + + ) : null} {data.run.available ? ( diff --git a/hub/client/pages/learnings-page/types.ts b/hub/client/pages/learnings-page/types.ts index d7b62a47..6a9a8a5b 100644 --- a/hub/client/pages/learnings-page/types.ts +++ b/hub/client/pages/learnings-page/types.ts @@ -41,7 +41,7 @@ export type LearningsPageData = usage: string | null } run: { path: string; available: boolean } - agentsPath: string + agentsPath: string | null loadError: string | null identityNotice: string | null library: LearningsLibraryData From ddcae203f5f1186f3432c291f3f73e0afa19f54d Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 23:32:17 -0800 Subject: [PATCH 15/17] fix(hub): add standard timestamps to agent connection tables Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25291e01-0146-42cb-ac6d-f5e1dd5c35f5 --- hub/schema/agent-authorization.prisma | 4 ++++ hub/schema/agent-client.prisma | 1 + hub/schema/agent-connection.prisma | 1 + .../migrations/20261223170000_agent_connections/migration.sql | 4 ++++ 4 files changed, 10 insertions(+) diff --git a/hub/schema/agent-authorization.prisma b/hub/schema/agent-authorization.prisma index 26aa0f13..d6fa138f 100644 --- a/hub/schema/agent-authorization.prisma +++ b/hub/schema/agent-authorization.prisma @@ -17,6 +17,10 @@ model AgentAuthorization { approvedAt DateTime? @map("approved_at") @db.Timestamptz(3) consumedAt DateTime? @map("consumed_at") @db.Timestamptz(3) + // Timestamp columns + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(3) + @@index([clientId]) @@index([sessionId]) @@index([expiresAt]) diff --git a/hub/schema/agent-client.prisma b/hub/schema/agent-client.prisma index 06b3164a..4ac73127 100644 --- a/hub/schema/agent-client.prisma +++ b/hub/schema/agent-client.prisma @@ -12,6 +12,7 @@ model AgentClient { // Timestamp columns createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(3) @@map("agent_clients") } diff --git a/hub/schema/agent-connection.prisma b/hub/schema/agent-connection.prisma index 7a40fbde..adf899ab 100644 --- a/hub/schema/agent-connection.prisma +++ b/hub/schema/agent-connection.prisma @@ -23,6 +23,7 @@ model AgentConnection { // Timestamp columns createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(3) @@index([clientId]) @@index([externalIdentityId]) diff --git a/hub/schema/migrations/20261223170000_agent_connections/migration.sql b/hub/schema/migrations/20261223170000_agent_connections/migration.sql index e74b176c..c65a0648 100644 --- a/hub/schema/migrations/20261223170000_agent_connections/migration.sql +++ b/hub/schema/migrations/20261223170000_agent_connections/migration.sql @@ -10,6 +10,8 @@ CREATE TABLE "agent_authorizations" ( "expires_at" TIMESTAMPTZ(3) NOT NULL, "approved_at" TIMESTAMPTZ(3), "consumed_at" TIMESTAMPTZ(3), + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, CONSTRAINT "agent_authorizations_pkey" PRIMARY KEY ("id") ); @@ -20,6 +22,7 @@ CREATE TABLE "agent_clients" ( "name" VARCHAR(200) NOT NULL, "redirect_uris" TEXT[], "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, CONSTRAINT "agent_clients_pkey" PRIMARY KEY ("id") ); @@ -39,6 +42,7 @@ CREATE TABLE "agent_connections" ( "last_used_at" TIMESTAMPTZ(3), "revoked_at" TIMESTAMPTZ(3), "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, CONSTRAINT "agent_connections_pkey" PRIMARY KEY ("id") ); From 170424ab85c3e31c9053ea00b6b7cda2eef657f1 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 23:32:17 -0800 Subject: [PATCH 16/17] test(hub): cover agent code replay, token refresh, and agent-side revocation Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25291e01-0146-42cb-ac6d-f5e1dd5c35f5 --- .../routes/agent-connections/index.db.test.ts | 107 +++++++++++++++--- 1 file changed, 91 insertions(+), 16 deletions(-) diff --git a/hub/server/routes/agent-connections/index.db.test.ts b/hub/server/routes/agent-connections/index.db.test.ts index 81908a6a..fe097500 100644 --- a/hub/server/routes/agent-connections/index.db.test.ts +++ b/hub/server/routes/agent-connections/index.db.test.ts @@ -47,6 +47,7 @@ it("connects an agent with the person's approval and stops it after they revoke product, agentConnections: { applicationOrigin: origin, + databaseUrl: process.env.DATABASE_URL!, learning: { cliPath: "/missing/cli.mjs", nodePath: "node", @@ -128,29 +129,71 @@ it("connects an agent with the person's approval and stops it after they revoke .getSetCookie() .find((cookie) => cookie.startsWith("hub_session="))! .split(";", 1)[0]! - function browser(path: string, method = "GET") { - return fetch(origin + path, { method, headers: { Cookie: session, Origin: origin } }) + function browser(path: string, method = "GET", body?: unknown) { + return fetch(origin + path, { + method, + headers: { + Cookie: session, + Origin: origin, + ...(body ? { "Content-Type": "application/json" } : {}), + }, + body: body ? JSON.stringify(body) : undefined, + }) } - expect(await (await browser(authorizationPath)).json()).toMatchObject({ agent: "Test agent" }) + const pending = (await (await browser(authorizationPath)).json()) as { + agent: string + redirectUri: string + session: string + } + expect(pending).toMatchObject({ agent: "Test agent", redirectUri }) + // A page loaded under a different account must not approve for this one. + expect( + (await browser(`${authorizationPath}/approve`, "POST", { session: "other" })).status, + ).toBe(409) const { redirectUrl } = (await ( - await browser(`${authorizationPath}/approve`, "POST") + await browser(`${authorizationPath}/approve`, "POST", { session: pending.session }) ).json()) as { redirectUrl: string } const returned = new URL(redirectUrl) expect(returned.searchParams.get("state")).toBe("agent-state") - expect((await browser(`${authorizationPath}/approve`, "POST")).status).toBe(410) + expect( + (await browser(`${authorizationPath}/approve`, "POST", { session: pending.session })).status, + ).toBe(410) - const tokens = (await ( - await fetch(`${origin}/token`, { + function requestTokens(fields: Record) { + return fetch(`${origin}/token`, { method: "POST", body: new URLSearchParams(fields) }) + } + const codeExchange = { + grant_type: "authorization_code", + client_id: registered.client_id, + code: returned.searchParams.get("code")!, + redirect_uri: redirectUri, + } + expect((await requestTokens({ ...codeExchange, code_verifier: "wrong" })).status).toBe(400) + const firstTokens = (await ( + await requestTokens({ ...codeExchange, code_verifier: verifier }) + ).json()) as { access_token: string; refresh_token: string } + expect((await requestTokens({ ...codeExchange, code_verifier: verifier })).status).toBe(400) + + const otherClient = (await ( + await fetch(`${origin}/register`, { method: "POST", - body: new URLSearchParams({ - grant_type: "authorization_code", - client_id: registered.client_id, - code: returned.searchParams.get("code")!, - code_verifier: verifier, - redirect_uri: redirectUri, - }), + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ client_name: "Other agent", redirect_uris: [redirectUri] }), }) - ).json()) as { access_token: string } + ).json()) as { client_id: string } + function refreshWith(clientId: string, refreshToken: string) { + return requestTokens({ + grant_type: "refresh_token", + client_id: clientId, + refresh_token: refreshToken, + }) + } + expect((await refreshWith(otherClient.client_id, firstTokens.refresh_token)).status).toBe(400) + const tokens = (await ( + await refreshWith(registered.client_id, firstTokens.refresh_token) + ).json()) as { access_token: string; refresh_token: string } + expect((await callMcp(firstTokens.access_token)).status).toBe(401) + expect((await refreshWith(registered.client_id, firstTokens.refresh_token)).status).toBe(400) // Local sign-in cannot read GitHub repositories, so the token works but access stops // at the repository check. @@ -163,11 +206,43 @@ it("connects an agent with the person's approval and stops it after they revoke const connectionId = listed.connections[0]!.id expect((await browser(`/api/agent-connections/${connectionId}`, "DELETE")).status).toBe(204) expect((await callMcp(tokens.access_token)).status).toBe(401) + + // An agent can also give up its own access through the standard revocation endpoint. + const again = await fetch( + `${origin}/authorize?${new URLSearchParams({ + response_type: "code", + client_id: registered.client_id, + redirect_uri: redirectUri, + code_challenge: createHash("sha256").update(verifier).digest("base64url"), + code_challenge_method: "S256", + })}`, + { redirect: "manual" }, + ) + const againPath = `/api/agent-connections/authorizations/${again.headers.get("location")!.split("/").at(-1)}` + const againApproved = (await ( + await browser(`${againPath}/approve`, "POST", { session: pending.session }) + ).json()) as { redirectUrl: string } + const agentTokens = (await ( + await requestTokens({ + ...codeExchange, + code: new URL(againApproved.redirectUrl).searchParams.get("code")!, + code_verifier: verifier, + }) + ).json()) as { access_token: string } + const revoked = await fetch(`${origin}/revoke`, { + method: "POST", + body: new URLSearchParams({ + client_id: registered.client_id, + token: agentTokens.access_token, + }), + }) + expect(revoked.status).toBe(200) + expect((await callMcp(agentTokens.access_token)).status).toBe(401) expect( await prisma.securityAudit.count({ where: { action: { in: ["agent_connection.approve", "agent_connection.revoke"] } }, }), - ).toBe(2) + ).toBe(4) } finally { if (server.listening) { await new Promise((resolve, reject) => { From 5492d4078cbde0e37f823a25f72ef19c0ece12a9 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Wed, 25 Nov 2026 23:32:29 -0800 Subject: [PATCH 17/17] docs(hub): describe agent approval checks, serialized commands, and self-revocation Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25291e01-0146-42cb-ac6d-f5e1dd5c35f5 --- hub/docs/learning-foundation.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/hub/docs/learning-foundation.md b/hub/docs/learning-foundation.md index 20ebb558..598b790a 100644 --- a/hub/docs/learning-foundation.md +++ b/hub/docs/learning-foundation.md @@ -115,7 +115,7 @@ A coding agent can read a repository's learnings from Hub and report which ones { "mcpServers": { "replica": { "url": "https://hub.example.com/mcp/repositories/" } } } ``` -The configuration holds no credential. The first time the agent calls Hub, it gets a `401` that points to Hub's OAuth discovery document. An agent that supports [MCP authorization](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization) registers itself, opens `/agents/approve/:authorizationId` in the browser, and waits. The person signs in if needed and approves or cancels. Hub then sends the browser back to the agent with a one-time code, and the agent trades the code for tokens. +The configuration holds no credential. The first time the agent calls Hub, it gets a `401` that points to Hub's OAuth discovery document. An agent that supports [MCP authorization](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization) registers itself, opens `/agents/approve/:authorizationId` in the browser, and waits. The person signs in if needed and approves or cancels. The page shows the address the agent asked Hub to send access to, and warns when that address is not on the person's computer. If they switch accounts in another tab before deciding, Hub asks them to review the request again. Hub then sends the browser back to the agent with a one-time code, and the agent trades the code for tokens. The agent gets the same tools and instructions as `replica-learning mcp` in the [learning package](../../packages/learning/README.md#connect-an-agent), because Hub loads them from the installed package. Hub supplies the backend: @@ -123,7 +123,7 @@ The agent gets the same tools and instructions as `replica-learning mcp` in the - `report_usage` records which learnings the agent applied. It refuses screenshots for now. - `submit_session` is refused, because Hub does not collect agent sessions yet. -Every request acts for the person who approved the connection. Hub rechecks their sign-in, membership, provider, and repository access each time, so ending the person's sessions or removing their access stops the agent too. A connection works for any repository the person can read, which is why the list is kept per person. People review and revoke their agents on the same page. Approving and revoking write security audits. +Every request acts for the person who approved the connection. Hub rechecks their sign-in, membership, provider, and repository access before and after each command, so ending the person's sessions or removing their access stops the agent too. Agent commands take the same lock as other learning work, so they run one at a time and an agent that arrives while Hub is busy is asked to try again. A connection works for any repository the person can read, which is why the list is kept per person. People review and revoke their agents on the same page, and an agent can give up its own access through `/revoke`. Approving and revoking write security audits. Tokens use the same lifetimes as Canvas connections. An approval request expires after 10 minutes. Access tokens last seven days, refresh tokens rotate on use, and a connection unused for 30 days ends. Hub stores only digests of codes and tokens. Every agent is a public OAuth client that relies on PKCE, because agents run on people's machines and cannot keep a secret. @@ -134,7 +134,7 @@ The OAuth endpoints are `/.well-known/oauth-authorization-server`, `/.well-known - `GET /api/agent-connections` - `DELETE /api/agent-connections/:connectionId` -The MCP endpoint accepts `POST` only and needs `HUB_APPLICATION_ORIGIN` and the learning package. Local repositories are not supported, because learnings belong to GitHub repositories. +The MCP endpoint accepts `POST` only and needs `HUB_APPLICATION_ORIGIN` and the learning package. Local repositories are not supported, because learnings belong to GitHub repositories, so their Learnings page offers no agent setup. ## Configuration