diff --git a/hub/client/application/hub-application/index.tsx b/hub/client/application/hub-application/index.tsx index 5e67638e3..ff0cca245 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 000000000..024922930 --- /dev/null +++ b/hub/client/application/hub/agent-connections/contract.ts @@ -0,0 +1,29 @@ +import { z } from "zod" + +export const agentAuthorizationSchema = z + .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() + +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 57fb007ab..4818cc8ae 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 000000000..9609fd993 --- /dev/null +++ b/hub/client/application/hub/routes/agent-approval/index.tsx @@ -0,0 +1,95 @@ +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 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, + } + 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 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", + 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) + } 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 000000000..b5bf475bd --- /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 0d0b79f60..1e9875149 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 761f0a9cd..83feabcf7 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 e8146c27b..00cf3739e 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,10 @@ export function settingsLearnings( ? null : `Copilot used ${formatCredits(state.usageCredits)} for this repository in the last 30 days.`, }, + // 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.test.tsx b/hub/client/pages/agent-connections-page/index.test.tsx new file mode 100644 index 000000000..9471050e9 --- /dev/null +++ b/hub/client/pages/agent-connections-page/index.test.tsx @@ -0,0 +1,74 @@ +import { fireEvent, render, screen, within } from "@testing-library/react" +import { describe, expect, it, vi } from "vitest" + +import { HubThemeProvider } from "@hooks/use-hub-theme" + +import { AgentConnectionsPage } from "." + +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 } }) + render( + , + { wrapper: HubThemeProvider }, + ) + + const config = screen.getByLabelText("Hub MCP configuration") + expect(config).toHaveTextContent("https://hub.example.com/mcp/repositories/2001") + expect(config).not.toHaveTextContent(/token|secret|password/i) + fireEvent.click(screen.getByRole("button", { name: "Copy: Hub MCP configuration" })) + + expect( + await screen.findByRole("button", { name: "Copied: Hub MCP configuration" }), + ).toBeVisible() + expect(writeText).toHaveBeenCalledWith(config.textContent) + }) + + it("asks for confirmation before revoking only the chosen agent", () => { + render( + , + { wrapper: HubThemeProvider }, + ) + + fireEvent.click(screen.getByRole("button", { name: "Revoke Local MCP client access" })) + + 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 new file mode 100644 index 000000000..7ea8423fb --- /dev/null +++ b/hub/client/pages/agent-connections-page/index.tsx @@ -0,0 +1,168 @@ +import { useRef, useState } from "react" +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" +import "./styles.css" + +/** + * 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 connectionsHeadingRef = useRef(null) + + if (data.view === "approval") { + return ( +
+
+ + 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 + 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 selectedConnection = data.connections.find(({ id }) => id === connectionToRevoke) + + return ( +
+
+ + Connect an agent + + + Set up an agent to use learning guidance from {data.repositoryName}. + +
+ +
+ + Add Hub to your agent + + {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. + )} +
+ +
+ + Your connected agents + + + Connected as @{data.signedInAs}. These agents can use your Hub access for any repository + you can access. + + {data.connections.length ? ( +
    + {data.connections.map((connection) => ( +
  • +
    + {connection.name} + + {connection.connectedLabel} · {connection.lastUsedLabel} + +
    + +
  • + ))} +
+ ) : ( + No agents are connected to your Hub account. + )} +
+ + {selectedConnection ? ( + setConnectionToRevoke(null)} + > +
setConnectionToRevoke(null)} + > + + + {selectedConnection.name} will no longer be able to use your Hub account. This does + not sign you out of Hub or change your repository access. + +
+ + +
+
+
+ ) : null} + {data.notice ? : null} +
+ ) +} diff --git a/hub/client/pages/agent-connections-prototype/stories.tsx b/hub/client/pages/agent-connections-page/stories.tsx similarity index 55% rename from hub/client/pages/agent-connections-prototype/stories.tsx rename to hub/client/pages/agent-connections-page/stories.tsx index 56775d479..4cac93c4a 100644 --- a/hub/client/pages/agent-connections-prototype/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,59 @@ 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", + 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", } 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 + // 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 type Story = StoryObj @@ -80,27 +91,27 @@ 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 = { - 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" }) - }, +} +export const RemoteApprovalRequest: Story = { + args: { data: { ...approval, destination: "agent.example.net", localDestination: false } }, } diff --git a/hub/client/pages/agent-connections-prototype/styles.css b/hub/client/pages/agent-connections-page/styles.css similarity index 87% rename from hub/client/pages/agent-connections-prototype/styles.css rename to hub/client/pages/agent-connections-page/styles.css index 199e1f760..e368b5699 100644 --- a/hub/client/pages/agent-connections-prototype/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 new file mode 100644 index 000000000..6b66d8ba6 --- /dev/null +++ b/hub/client/pages/agent-connections-page/types.ts @@ -0,0 +1,30 @@ +export interface AgentConnection { + id: string + name: string + connectedLabel: string + lastUsedLabel: string + revokePath: string +} + +export type AgentConnectionsPageData = + | { + view: "connections" + repositoryName: 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 + } + | { + 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/client/pages/agent-connections-prototype/index.test.tsx b/hub/client/pages/agent-connections-prototype/index.test.tsx deleted file mode 100644 index 69c2c23d8..000000000 --- a/hub/client/pages/agent-connections-prototype/index.test.tsx +++ /dev/null @@ -1,117 +0,0 @@ -import { fireEvent, render, screen, within } from "@testing-library/react" -import { describe, expect, it, vi } from "vitest" - -import { HubThemeProvider } from "@hooks/use-hub-theme" - -import { AgentConnectionsPrototype } from "." -import type { AgentConnectionsPrototypeData } from "./types" - -function renderPrototype(data: AgentConnectionsPrototypeData) { - render(, { wrapper: HubThemeProvider }) -} - -describe("AgentConnectionsPrototype()", () => { - it("copies a repository MCP endpoint 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) - - const config = screen.getByLabelText("Hub MCP configuration") - expect(config).toHaveTextContent("https://hub.example.com/mcp/repositories/2001") - expect(config).not.toHaveTextContent(/token|secret|password/i) - fireEvent.click(screen.getByRole("button", { name: "Copy: Hub MCP configuration" })) - - expect( - await screen.findByRole("button", { name: "Copied: Hub MCP configuration" }), - ).toBeVisible() - 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("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() - }) - - 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() - }) -}) diff --git a/hub/client/pages/agent-connections-prototype/index.tsx b/hub/client/pages/agent-connections-prototype/index.tsx deleted file mode 100644 index 8fbc4ea3f..000000000 --- a/hub/client/pages/agent-connections-prototype/index.tsx +++ /dev/null @@ -1,156 +0,0 @@ -import { useRef, useState } from "react" -import { Button, Heading, Text } from "@primer/react-brand" - -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 "./styles.css" - -export function AgentConnectionsPrototype({ data }: { data: AgentConnectionsPrototypeData }) { - const [connections, setConnections] = useState(data.connections) - 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.`} - -
- )} -
- ) - } - - return ( -
-
- - Connect an agent - - - Set up an agent to use learning guidance from {data.repositoryName}. - -
- -
- - 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. - - -
- -
- - Your connected agents - - - Connected as {data.signedInAs}. These agents can use your Hub access for any repository - you can access. - - {connections.length ? ( -
    - {connections.map((connection) => ( -
  • -
    - {connection.name} - - Connected{" "} - - {" · "}Last used{" "} - - -
    - -
  • - ))} -
- ) : ( - No agents are connected to your Hub account. - )} -
- - {selectedConnection ? ( - setConnectionToRevoke(null)} - > -
- - {selectedConnection.name} will no longer be able to use your Hub account. This does - not sign you out of Hub or change your repository access. - -
- - -
-
-
- ) : null} - {notice ? : null} -
- ) -} diff --git a/hub/client/pages/agent-connections-prototype/types.ts b/hub/client/pages/agent-connections-prototype/types.ts deleted file mode 100644 index 146d4bced..000000000 --- a/hub/client/pages/agent-connections-prototype/types.ts +++ /dev/null @@ -1,24 +0,0 @@ -export interface AgentConnection { - id: string - name: string - connectedAt: string - lastUsedAt: string -} - -interface AgentConnectionsPrototypeBase { - repositoryId: string - repositoryName: string - hubUrl: string - signedInAs: string -} - -export type AgentConnectionsPrototypeData = - | (AgentConnectionsPrototypeBase & { - view: "connections" - connections: AgentConnection[] - }) - | (AgentConnectionsPrototypeBase & { - view: "approval" - connections: AgentConnection[] - requestingAgent: string - }) diff --git a/hub/client/pages/learnings-page/index.tsx b/hub/client/pages/learnings-page/index.tsx index e02dca6fc..1a34e6500 100644 --- a/hub/client/pages/learnings-page/index.tsx +++ b/hub/client/pages/learnings-page/index.tsx @@ -81,14 +81,21 @@ function LearningsContent({ title={copy.heading} description={copy.description} trailing={ - data.run.available ? ( -
- - -
- ) : null + ) : 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 85e54a8dd..57558d9ee 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 dc042ba55..a57d95aff 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 674221c0f..6a9a8a5b4 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 | null loadError: string | null identityNotice: string | null library: LearningsLibraryData diff --git a/hub/docs/learning-foundation.md b/hub/docs/learning-foundation.md index 6e433dbd3..598b790a8 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. 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: + +- `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 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. + +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, so their Learnings page offers no agent setup. + ## Configuration | Variable | Contract | diff --git a/hub/package-lock.json b/hub/package-lock.json index 0e36e7484..790336da6 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 f5dbddc33..8a11e9c97 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", diff --git a/hub/schema/agent-authorization.prisma b/hub/schema/agent-authorization.prisma new file mode 100644 index 000000000..d6fa138fe --- /dev/null +++ b/hub/schema/agent-authorization.prisma @@ -0,0 +1,28 @@ +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) + + // 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]) + @@map("agent_authorizations") +} diff --git a/hub/schema/agent-client.prisma b/hub/schema/agent-client.prisma new file mode 100644 index 000000000..4ac73127a --- /dev/null +++ b/hub/schema/agent-client.prisma @@ -0,0 +1,18 @@ +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) + 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 new file mode 100644 index 000000000..adf899abc --- /dev/null +++ b/hub/schema/agent-connection.prisma @@ -0,0 +1,33 @@ +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) + updatedAt DateTime @default(now()) @updatedAt @map("updated_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 74d96f416..1069a40f6 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 510cfe1e2..125afdb67 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 9037094c9..1e385f804 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 eef1d1061..58d611416 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 000000000..c65a0648b --- /dev/null +++ b/hub/schema/migrations/20261223170000_agent_connections/migration.sql @@ -0,0 +1,96 @@ +-- 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), + "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") +); + +-- 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, + "updated_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, + "updated_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; diff --git a/hub/server/create-app/index.ts b/hub/server/create-app/index.ts index 9d3f48b7e..905e1a189 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,18 @@ export function createApp({ app.use( [ "/api/canvas", + "/api/agent-connections", "/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", @@ -57,6 +68,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 000000000..458255bb2 --- /dev/null +++ b/hub/server/domains/agent-connections/create-agent-connections/index.ts @@ -0,0 +1,233 @@ +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, + redirectUri: pending.redirectUri, + } + ) + }, + + 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, + clientId: pending.clientId, + }) + } + 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) { + 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 reference = canvasAuthorityReference(browser.viewer) + return reference ? listAgentConnections(database, reference) : Promise.resolve([]) + }, + + 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.test.ts b/hub/server/domains/agent-connections/create-learning-mcp-backend/index.test.ts new file mode 100644 index 000000000..696d3058e --- /dev/null +++ b/hub/server/domains/agent-connections/create-learning-mcp-backend/index.test.ts @@ -0,0 +1,156 @@ +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" + +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({ + 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 failure = backend.listLearnings({}) + + 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 new file mode 100644 index 000000000..193ead614 --- /dev/null +++ b/hub/server/domains/agent-connections/create-learning-mcp-backend/index.ts @@ -0,0 +1,227 @@ +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" + +const agentErrorCodes = new Set([ + "conflict", + "invalid_input", + "invalid_transition", + "not_found", + "unsupported", +]) + +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 +} + +/** 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 + 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 + } + } + + /** + * 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 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. + if (error instanceof LearningCommandError && agentErrorCodes.has(error.code)) + throw toAgentError(error.code, error.message) + throw error + } + } + + 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}`]), + ] + } + + 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 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 }[] + } + // 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.") + return withPrivateFile(JSON.stringify(report), (file) => + run(directory, ["report-usage", file]), + ) + }, + + 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 d86633089..7b18b1257 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,14 @@ try { { scopeGitHubMembers: authenticationConfiguration.githubConfigured }, ) learnings = learningDependencies + const agentApplicationOrigin = authenticationEnvironment.HUB_APPLICATION_ORIGIN + if (learningConfiguration && agentApplicationOrigin) { + agentConnections = { + applicationOrigin: agentApplicationOrigin, + databaseUrl, + learning: learningConfiguration, + } + } if (decisionRuntimeConfiguration) { const applicationOrigin = authenticationEnvironment.HUB_APPLICATION_ORIGIN if (!storage || !learningConfiguration || !applicationOrigin) { @@ -369,6 +379,7 @@ try { await runApi({ ...configuration, logger, + agentConnections, agentVisualCritic, isReady: isStorageReady, authentication, @@ -391,6 +402,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 3f8cfe996..862f7ed8e 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 000000000..a137cdac3 --- /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 000000000..138336c15 --- /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/agent-oauth-provider/index.ts b/hub/server/integrations/mcp/agent-oauth-provider/index.ts new file mode 100644 index 000000000..7af308bea --- /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 000000000..37bd0a6ce --- /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 new file mode 100644 index 000000000..d13205634 --- /dev/null +++ b/hub/server/integrations/mcp/create-agent-auth-router/index.ts @@ -0,0 +1,23 @@ +import type { RequestHandler } from "express" +import { mcpAuthRouter } from "@modelcontextprotocol/sdk/server/auth/router.js" + +import { agentOAuthProvider } from "../agent-oauth-provider/index.ts" +import type { AgentOAuthService } from "../agent-oauth-provider/types.ts" + +export const agentMcpPath = "/mcp" + +/** + * 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 000000000..bcf3b4e2b --- /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 000000000..7330ec466 --- /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 000000000..6480403ae --- /dev/null +++ b/hub/server/integrations/mcp/require-agent-token/index.ts @@ -0,0 +1,23 @@ +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 { 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 + * 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 000000000..592257256 --- /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 000000000..1d871f186 --- /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 000000000..87b71db33 --- /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 000000000..1707b01c5 --- /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 000000000..01e0f9a4a --- /dev/null +++ b/hub/server/repositories/agent-authorizations/find-pending-agent-authorization/index.ts @@ -0,0 +1,18 @@ +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, + clientId: 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 000000000..316ae8658 --- /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 000000000..2c79388ed --- /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 000000000..2dcb145f8 --- /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 000000000..65e8945c7 --- /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 000000000..8c55133bb --- /dev/null +++ b/hub/server/repositories/agent-connections/list-agent-connections/index.ts @@ -0,0 +1,20 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" +import type { CanvasAuthorityReference } from "../../canvas/authority/index.ts" + +export function listAgentConnections( + database: Pick, + owner: CanvasAuthorityReference, +) { + 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 000000000..848f9d9e5 --- /dev/null +++ b/hub/server/repositories/agent-connections/record-agent-connection-audit/index.ts @@ -0,0 +1,24 @@ +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 } | { clientId: string }), +) { + // 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: input.action, + outcome: "SUCCESS", + ...target, + context: { actorMembershipId: input.actorMembershipId }, + }, + }) +} 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 000000000..3c35abbe9 --- /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 000000000..e16b8a6e2 --- /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 000000000..e66e59a54 --- /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 000000000..fe097500f --- /dev/null +++ b/hub/server/routes/agent-connections/index.db.test.ts @@ -0,0 +1,253 @@ +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, + databaseUrl: process.env.DATABASE_URL!, + 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", body?: unknown) { + return fetch(origin + path, { + method, + headers: { + Cookie: session, + Origin: origin, + ...(body ? { "Content-Type": "application/json" } : {}), + }, + body: body ? JSON.stringify(body) : undefined, + }) + } + 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", { 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", { session: pending.session })).status, + ).toBe(410) + + 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", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ client_name: "Other agent", redirect_uris: [redirectUri] }), + }) + ).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. + 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) + + // 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(4) + } 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 000000000..9b622abb8 --- /dev/null +++ b/hub/server/routes/agent-connections/index.ts @@ -0,0 +1,237 @@ +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 { 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" + +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, databaseUrl, 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.") + // 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 + 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, + redirectUri: pending.redirectUri, + session: session.sessionId, + 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 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, { + 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 000000000..315765971 --- /dev/null +++ b/hub/server/routes/agent-connections/types.ts @@ -0,0 +1,11 @@ +export interface AgentConnectionRouteDependencies { + applicationOrigin: string + databaseUrl: 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 4986bd557..7efb061bd 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": @@ -499,6 +501,10 @@ function contextFor(record: SecurityAuditListRecord): Record Promise + agentConnections?: AgentConnectionRouteDependencies agentVisualCritic?: AgentVisualCriticRouteDependencies authentication?: AuthenticationRouteDependencies copilotConnection?: CopilotConnectionRouteDependencies diff --git a/hub/vite.config.ts b/hub/vite.config.ts index ed83c66cb..48d51024b 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] }, diff --git a/packages/learning/README.md b/packages/learning/README.md index 88dd05506..c9e7d977b 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 09d93107f..574ea1f4a 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 ebd4ecbb5..6ba474508 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 033417e61..0e570ea97 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 3d0df2247..68885d2c7 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)