Repository navigation
feat(hub): host learning MCP with agent connections #389
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
nshki
wants to merge
17
commits into
nshki/feat/hub/learning-activity
from
nshki/feat/hub/learning-mcp
Draft
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
723e0f3
feat(learning): read learnings as agents see them
nshki d52b127
chore(hub): add the MCP SDK
nshki 9a4177a
feat(hub): store agent clients, approvals, and connections
nshki de7b91c
feat(hub): host the learning MCP server behind agent sign-in
nshki 2aa7afc
feat(hub): let people approve and revoke agent connections
nshki e95961f
docs(hub): explain how to connect an agent to Hub
nshki bcf84d7
fix(hub): keep server details out of agent error messages
nshki af20648
refactor(hub): move the agent OAuth provider into its own module
nshki 06e85aa
fix(hub): log and proxy agent connection endpoints like other sign-in…
nshki 9ee2206
fix(hub): run agent learning commands one at a time and recheck access
nshki 9051c34
fix(hub): tie agent approval to the shown account and show where acce…
nshki 21e2810
fix(hub): keep agent page stories from submitting their forms
nshki 111cb55
fix(hub): audit agent revocations and list only usable connections
nshki 960325f
fix(hub): hide agent setup for local repositories
nshki ddcae20
fix(hub): add standard timestamps to agent connection tables
nshki 170424a
test(hub): cover agent code replay, token refresh, and agent-side rev…
nshki 5492d40
docs(hub): describe agent approval checks, serialized commands, and s…
nshki File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
95 changes: 95 additions & 0 deletions
95
hub/client/application/hub/routes/agent-approval/index.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 <HubApplication canvasReturnTo={loaderData.browserPath} /> | ||
| const busy = fetcher.state !== "idle" | ||
| return ( | ||
| <FormBoundary | ||
| busy={busy} | ||
| error={busy ? null : fetcher.data?.error} | ||
| onSubmit={(form) => void fetcher.submit(form, { method: "post", action: pathname })} | ||
| > | ||
| <AgentConnectionsPage busy={busy} data={loaderData.page} /> | ||
| </FormBoundary> | ||
| ) | ||
| } |
103 changes: 103 additions & 0 deletions
103
hub/client/application/hub/routes/learning-agents/index.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<WorkspaceResponse | null>() | ||
| 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 ( | ||
| <FormBoundary | ||
| busy={busy} | ||
| error={busy ? null : fetcher.data?.error} | ||
| onSubmit={(form) => void fetcher.submit(form, { method: "post", action: pathname })} | ||
| > | ||
| <AgentConnectionsPage | ||
| busy={busy} | ||
| data={{ | ||
| view: "connections", | ||
| repositoryName: repository?.nameWithOwner ?? "this repository", | ||
| mcpUrl: repository?.capabilities?.local ? null : loaderData.mcpUrl, | ||
| signedInAs: workspace?.viewer.login ?? "", | ||
| connections: loaderData.connections, | ||
| notice: busy ? null : (fetcher.data?.notice ?? null), | ||
| }} | ||
| /> | ||
| </FormBoundary> | ||
| ) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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( | ||
| <AgentConnectionsPage | ||
| data={{ | ||
| view: "connections", | ||
| repositoryName: "github/prototype", | ||
| mcpUrl: "https://hub.example.com/mcp/repositories/2001", | ||
| signedInAs: "octocat", | ||
| notice: null, | ||
| connections: [], | ||
| }} | ||
| />, | ||
| { 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( | ||
| <AgentConnectionsPage | ||
| data={{ | ||
| 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", | ||
| 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", | ||
| connectedLabel: "Connected 11/12/2026", | ||
| lastUsedLabel: "Not used yet", | ||
| revokePath: "/repositories/2001/learnings/agents/agent-local", | ||
| }, | ||
| ], | ||
| }} | ||
| />, | ||
| { 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") | ||
| }) | ||
| }) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.