From dbdb3fb7af5a86465da19e875c0557d4fc7c17ef Mon Sep 17 00:00:00 2001 From: Taskmaster-1 <126377225+Taskmaster-1@users.noreply.github.com> Date: Sat, 31 Oct 2026 21:24:50 +0530 Subject: [PATCH] App directory: 41 apps that connect in one click Connections gets an app directory of remote MCP servers, each checked live to sign in with dynamic client registration (or to need no sign-in): Jira and Confluence, Asana, Notion, Stripe, Intercom, Granola, Supabase, Sentry and more. Search, category filters, a starter ask on every card, and the connected app's asks show up on the home page. The server and its name come from the directory, so a click can't connect anything else. Fixes sign-in for every OAuth MCP server: the OAuth provider was created inside the connect call that failed, so the authorization URL it built was lost and the connection stuck at needs_auth with no way to authorize. --- README.md | 3 +- apps/server/src/catalog.test.ts | 114 +++++ apps/server/src/catalog.ts | 469 +++++++++++++++++++ apps/server/src/routes/connections.ts | 149 +++--- apps/web/app/(app)/automations/page.tsx | 5 +- apps/web/app/(app)/connections/directory.tsx | 201 ++++++++ apps/web/app/(app)/connections/page.tsx | 286 ++++------- apps/web/app/(app)/page.tsx | 11 +- apps/web/lib/api.ts | 22 +- docs/api.md | 5 +- docs/design.md | 3 +- docs/linear.md | 2 +- packages/tools/src/mcp/client.ts | 19 +- packages/tools/src/tools.test.ts | 65 +++ 14 files changed, 1061 insertions(+), 293 deletions(-) create mode 100644 apps/server/src/catalog.test.ts create mode 100644 apps/server/src/catalog.ts create mode 100644 apps/web/app/(app)/connections/directory.tsx diff --git a/README.md b/README.md index 8e07667..e9c0507 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,8 @@ Agent products that act in your tools share three problems: approvals that live - Built-in Google Sheets: read any sheet by link, add rows, update cells and create spreadsheets, each write shown as a table on the approval card ("save the invoice from that email and add its total to my Expenses sheet") - Automations triggered by a cron schedule, new Gmail messages matching a search, or a secret webhook URL - Reminders and follow-ups from chat: "remind me Friday at 9 to send the report" notifies you by push, Slack or email at that time; "in 3 days, check whether Sam replied and nudge him if not" brings the agent back to the same conversation, with its context, to do it. One-off or repeating, in your time zone, listed (and cancellable) under Automations. Scheduling from a task that read an email or web page always asks first, so outside content can't plant a scheduled instruction ([how it works](docs/api.md#scheduled-from-chat)) -- MCP connections over Streamable HTTP with OAuth 2.1 + PKCE, or bearer tokens; presets for GitHub, Linear, Notion, Atlassian, Sentry +- An app directory of 41 remote MCP servers that connect in one click (Notion, Jira and Confluence, Asana, Stripe, Intercom, Granola, Supabase, Sentry and more), each with starter asks; sign-in happens on the app's own site and its tools fall under your approval rules +- Any other MCP server over Streamable HTTP, with OAuth 2.1 + PKCE or a bearer token - Approval inbox, editable approvals, deny-with-reason, cancel now / after this step - Approve a plan, not every step: the agent proposes the exact actions it will take, you untick what you don't want, and the kept actions run without asking again (even after the task read outside content, because you saw each one, unless a step names a recipient that first appeared in that content) - Several pending actions from one step can be ticked and signed off together diff --git a/apps/server/src/catalog.test.ts b/apps/server/src/catalog.test.ts new file mode 100644 index 0000000..a6074c6 --- /dev/null +++ b/apps/server/src/catalog.test.ts @@ -0,0 +1,114 @@ +import { afterAll, beforeAll, expect, test } from "bun:test"; +import { schema } from "@synapse/db"; +import { createApp } from "./app"; +import { APP_CATEGORIES, CATALOG, catalogAppFor, sameServer } from "./catalog"; +import { loadConfig } from "./config"; +import { createServices, type Services } from "./services"; + +let services: Services; +let app: ReturnType; +const ORIGIN = "http://localhost:3000"; + +beforeAll(async () => { + services = await createServices( + loadConfig({ + NODE_ENV: "test", + DATABASE_URL: "pglite://memory", + SYNAPSE_SECRET: "t".repeat(40), + PUBLIC_URL: ORIGIN, + }), + ); + app = createApp(services); +}); +afterAll(() => services.close()); + +async function signUp(email: string) { + const res = await app.request("/api/auth/sign-up/email", { + method: "POST", + headers: { "content-type": "application/json", origin: ORIGIN }, + body: JSON.stringify({ email, password: "correct horse battery", name: "Ada" }), + }); + expect(res.status).toBe(200); + const cookie = res.headers + .getSetCookie() + .map((c) => c.split(";")[0]) + .join("; "); + const userId = ((await res.json()) as { user: { id: string } }).user.id; + const call = async (path: string, method = "GET") => { + const r = await app.request(path, { method, headers: { cookie, origin: ORIGIN } }); + const text = await r.text(); + // biome-ignore lint/suspicious/noExplicitAny: test responses are loosely typed JSON + return { status: r.status, json: text ? (JSON.parse(text) as Record) : null }; + }; + return { userId, call }; +} + +test("every directory entry is connectable as listed", () => { + const ids = new Set(); + for (const a of CATALOG) { + // The id becomes the connection name: the same rule POST /api/connections enforces. + expect(a.id).toMatch(/^[a-z0-9][a-z0-9-]*$/); + expect(ids.has(a.id)).toBe(false); + ids.add(a.id); + expect(new URL(a.url).protocol).toBe("https:"); + expect(APP_CATEGORIES).toContain(a.category); + expect(a.examples.length).toBeGreaterThan(0); + expect(CATALOG.filter((b) => sameServer(a.url, b.url))).toHaveLength(1); + } + for (const c of APP_CATEGORIES) expect(CATALOG.some((a) => a.category === c)).toBe(true); +}); + +test("sameServer ignores host case and trailing slashes, nothing else", () => { + expect(sameServer("https://mcp.notion.com/mcp", "https://MCP.notion.com/mcp/")).toBe(true); + expect(sameServer("https://mcp.stripe.com", "https://mcp.stripe.com/")).toBe(true); + expect(sameServer("https://mcp.notion.com/mcp", "https://mcp.notion.com/sse")).toBe(false); + expect(sameServer("https://mcp.notion.com/mcp", "http://mcp.notion.com/mcp")).toBe(false); + expect(catalogAppFor("https://mcp.notion.com/mcp/")?.id).toBe("notion"); +}); + +test("directory marks what you've connected; connecting twice or unknown apps is refused", async () => { + const ada = await signUp("ada-directory@example.com"); + const bob = await signUp("bob-directory@example.com"); + + const before = await ada.call("/api/connections/catalog"); + expect(before.status).toBe(200); + expect(before.json!.categories).toEqual(APP_CATEGORIES); + expect(before.json!.apps).toHaveLength(CATALOG.length); + expect(before.json!.apps.every((a: { connectionId: unknown }) => a.connectionId === null)).toBe( + true, + ); + + // Connected earlier by hand, under another name and a slightly different URL. + const [row] = await services.database.db + .insert(schema.connections) + .values({ + userId: ada.userId, + name: "my notes", + url: "https://MCP.notion.com/mcp/", + status: "disabled", + auth: { type: "none" }, + }) + .returning(); + + const after = await ada.call("/api/connections/catalog"); + const notion = after.json!.apps.find((a: { id: string }) => a.id === "notion"); + expect(notion.connectionId).toBe(row!.id); + // Someone else's connections don't count. + const theirs = await bob.call("/api/connections/catalog"); + expect(theirs.json!.apps.find((a: { id: string }) => a.id === "notion").connectionId).toBe(null); + + const again = await ada.call("/api/connections/catalog/notion", "POST"); + expect(again.status).toBe(409); + expect(again.json!.error.message).toContain("Notion is already connected"); + + const unknown = await ada.call("/api/connections/catalog/not-an-app", "POST"); + expect(unknown.status).toBe(404); + + // The connection list names it the way the directory does and carries its starter asks. + const list = await ada.call("/api/connections"); + expect(list.json!.connections[0]).toMatchObject({ + name: "my notes", + title: "Notion", + examples: CATALOG.find((a) => a.id === "notion")!.examples, + }); +}); diff --git a/apps/server/src/catalog.ts b/apps/server/src/catalog.ts new file mode 100644 index 0000000..1c36642 --- /dev/null +++ b/apps/server/src/catalog.ts @@ -0,0 +1,469 @@ +import type { Effect } from "@synapse/core"; + +/** + * The app directory: remote MCP servers anyone can connect in one click. Each one either + * signs in with OAuth and registers our client on its own (dynamic client registration or a + * client ID metadata document), or needs no sign-in at all. Servers that need an app set up + * by hand first (an OAuth client id, a token) stay out of here; they still work as a custom + * server. Every tool they offer goes through the same effects and approval rules as the rest. + */ + +export type AppCategory = + | "Projects" + | "Docs & files" + | "Meetings" + | "Sales & support" + | "Payments" + | "Design & sites" + | "Engineering" + | "Data" + | "Research"; + +export const APP_CATEGORIES: AppCategory[] = [ + "Projects", + "Docs & files", + "Meetings", + "Sales & support", + "Payments", + "Design & sites", + "Engineering", + "Data", + "Research", +]; + +export interface CatalogApp { + /** Also the connection name, so tools show up as "__". No underscores. */ + id: string; + title: string; + url: string; + category: AppCategory; + /** One line: what the agent can do there. */ + description: string; + /** "none": public server, nothing to sign in to. */ + auth: "oauth" | "none"; + /** Things to ask once it's connected; shown in the directory and on the home page. */ + examples: string[]; + /** + * Effects for tools the server doesn't mark read-only, set when it's connected. Named one + * by one: a tool the server adds later still starts out asking first. + */ + toolEffects?: Record; +} + +export const CATALOG: CatalogApp[] = [ + // ── Projects ───────────────────────────────────────────────────────────── + { + id: "atlassian", + title: "Jira & Confluence", + url: "https://mcp.atlassian.com/v1/mcp", + category: "Projects", + description: "Search and update Jira issues, read and write Confluence pages.", + auth: "oauth", + examples: ["What Jira issues are assigned to me?", "Find the Confluence page on onboarding"], + }, + { + id: "asana", + title: "Asana", + url: "https://mcp.asana.com/mcp", + category: "Projects", + description: "Tasks, projects and goals in your Asana workspace.", + auth: "oauth", + examples: ["What's due in Asana this week?", "Summarise the status of my Asana projects"], + }, + { + id: "monday", + title: "monday.com", + url: "https://mcp.monday.com/mcp", + category: "Projects", + description: "Boards, items and updates on monday.com.", + auth: "oauth", + examples: ["What's stuck on my monday.com boards?"], + }, + { + id: "clickup", + title: "ClickUp", + url: "https://mcp.clickup.com/mcp", + category: "Projects", + description: "Tasks, lists and docs in ClickUp.", + auth: "oauth", + examples: ["What ClickUp tasks are overdue?"], + }, + { + id: "todoist", + title: "Todoist", + url: "https://ai.todoist.net/mcp", + category: "Projects", + description: "Your to-do list: add, find and complete tasks.", + auth: "oauth", + examples: ["What's on my Todoist today?", "Add the follow-ups from my last meeting to Todoist"], + }, + { + id: "linear-mcp", + title: "Linear (MCP)", + url: "https://mcp.linear.app/mcp", + category: "Projects", + description: "Linear's own server. The built-in Linear connection covers most needs.", + auth: "oauth", + examples: ["What's on my plate in Linear this week?"], + }, + + // ── Docs & files ───────────────────────────────────────────────────────── + { + id: "notion", + title: "Notion", + url: "https://mcp.notion.com/mcp", + category: "Docs & files", + description: "Search, read and write Notion pages and databases.", + auth: "oauth", + examples: [ + "Find my latest meeting notes in Notion", + "Turn this week's notes into a summary page", + ], + }, + { + id: "miro", + title: "Miro", + url: "https://mcp.miro.com/", + category: "Docs & files", + description: "Read boards and add stickies, frames and diagrams.", + auth: "oauth", + examples: ["Summarise the ideas on my latest Miro board"], + }, + + // ── Meetings ───────────────────────────────────────────────────────────── + { + id: "granola", + title: "Granola", + url: "https://mcp.granola.ai/mcp", + category: "Meetings", + description: "Your meeting notes and transcripts.", + auth: "oauth", + examples: [ + "What did we decide in yesterday's meetings?", + "List action items from my meetings this week", + ], + }, + { + id: "fireflies", + title: "Fireflies", + url: "https://api.fireflies.ai/mcp", + category: "Meetings", + description: "Meeting transcripts, summaries and action items.", + auth: "oauth", + examples: ["Summarise my last call with a customer"], + }, + { + id: "krisp", + title: "Krisp", + url: "https://mcp.krisp.ai/mcp", + category: "Meetings", + description: "Meeting notes and transcripts from Krisp.", + auth: "oauth", + examples: ["What action items came out of today's meetings?"], + }, + { + id: "cal", + title: "Cal.com", + url: "https://mcp.cal.com/mcp", + category: "Meetings", + description: "Event types, availability and bookings.", + auth: "oauth", + examples: ["What bookings do I have next week on Cal.com?"], + }, + + // ── Sales & support ────────────────────────────────────────────────────── + { + id: "intercom", + title: "Intercom", + url: "https://mcp.intercom.com/mcp", + category: "Sales & support", + description: "Customer conversations and contacts.", + auth: "oauth", + examples: ["What are customers asking about most this week?"], + }, + { + id: "attio", + title: "Attio", + url: "https://mcp.attio.com/mcp", + category: "Sales & support", + description: "Your CRM: people, companies, deals and notes.", + auth: "oauth", + examples: ["Which deals in Attio haven't moved in two weeks?"], + }, + { + id: "close", + title: "Close", + url: "https://mcp.close.com/mcp", + category: "Sales & support", + description: "Leads, opportunities and activity in Close.", + auth: "oauth", + examples: ["Which leads in Close need a follow-up?"], + }, + + // ── Payments ───────────────────────────────────────────────────────────── + { + id: "stripe", + title: "Stripe", + url: "https://mcp.stripe.com", + category: "Payments", + description: "Customers, payments, invoices and subscriptions.", + auth: "oauth", + examples: ["How much revenue came in this week?", "List failed payments from the last 7 days"], + }, + { + id: "paypal", + title: "PayPal", + url: "https://mcp.paypal.com/mcp", + category: "Payments", + description: "Invoices, orders and transactions.", + auth: "oauth", + examples: ["Which PayPal invoices are still unpaid?"], + }, + { + id: "square", + title: "Square", + url: "https://mcp.squareup.com/mcp", + category: "Payments", + description: "Payments, orders, catalog and customers.", + auth: "oauth", + examples: ["What were my Square sales yesterday?"], + }, + { + id: "ramp", + title: "Ramp", + url: "https://mcp.ramp.com/mcp", + category: "Payments", + description: "Company spend, cards and reimbursements.", + auth: "oauth", + examples: ["Where did our spend go this month?"], + }, + { + id: "mercury", + title: "Mercury", + url: "https://mcp.mercury.com/mcp", + category: "Payments", + description: "Bank accounts and transactions.", + auth: "oauth", + examples: ["Summarise this month's transactions in Mercury"], + }, + + // ── Design & sites ─────────────────────────────────────────────────────── + { + id: "canva", + title: "Canva", + url: "https://mcp.canva.com/mcp", + category: "Design & sites", + description: "Find, create and export Canva designs.", + auth: "oauth", + examples: ["Find my latest presentation in Canva"], + }, + { + id: "webflow", + title: "Webflow", + url: "https://mcp.webflow.com/mcp", + category: "Design & sites", + description: "Sites, pages and CMS collections.", + auth: "oauth", + examples: ["List the blog posts on my Webflow site"], + }, + { + id: "wix", + title: "Wix", + url: "https://mcp.wix.com/mcp", + category: "Design & sites", + description: "Your Wix sites, stores and bookings.", + auth: "oauth", + examples: ["What orders came in on my Wix store this week?"], + }, + { + id: "jotform", + title: "Jotform", + url: "https://mcp.jotform.com/", + category: "Design & sites", + description: "Forms and their submissions.", + auth: "oauth", + examples: ["Summarise this week's form submissions"], + }, + + // ── Engineering ────────────────────────────────────────────────────────── + { + id: "sentry", + title: "Sentry", + url: "https://mcp.sentry.dev/mcp", + category: "Engineering", + description: "Errors, issues and releases.", + auth: "oauth", + examples: ["What new errors showed up this week?"], + }, + { + id: "netlify", + title: "Netlify", + url: "https://mcp.netlify.com/mcp", + category: "Engineering", + description: "Sites, deploys and forms.", + auth: "oauth", + examples: ["Did my latest Netlify deploy succeed?"], + }, + { + id: "cloudflare", + title: "Cloudflare", + url: "https://mcp.cloudflare.com/mcp", + category: "Engineering", + description: "Your Cloudflare account: Workers, DNS, storage and more.", + auth: "oauth", + examples: ["List my Cloudflare Workers and when they last deployed"], + }, + { + id: "supabase", + title: "Supabase", + url: "https://mcp.supabase.com/mcp", + category: "Engineering", + description: "Projects, tables, queries and logs.", + auth: "oauth", + examples: ["How many users signed up this week?"], + }, + { + id: "neon", + title: "Neon", + url: "https://mcp.neon.tech/mcp", + category: "Engineering", + description: "Postgres projects, branches and queries.", + auth: "oauth", + examples: ["What tables are in my Neon database?"], + }, + { + id: "gitlab", + title: "GitLab", + url: "https://gitlab.com/api/v4/mcp", + category: "Engineering", + description: "Projects, issues and merge requests on gitlab.com.", + auth: "oauth", + examples: ["What merge requests are waiting on me?"], + }, + { + id: "semgrep", + title: "Semgrep", + url: "https://mcp.semgrep.ai/mcp", + category: "Engineering", + description: "Scan code for security issues.", + auth: "oauth", + examples: ["Scan this snippet for security issues"], + }, + { + id: "context7", + title: "Context7", + url: "https://mcp.context7.com/mcp", + category: "Engineering", + description: "Up-to-date docs for thousands of libraries. No sign-in.", + auth: "none", + examples: ["How do I set up middleware in the latest Hono?"], + }, + { + id: "deepwiki", + title: "DeepWiki", + url: "https://mcp.deepwiki.com/mcp", + category: "Engineering", + description: "Ask questions about any public GitHub repository. No sign-in.", + auth: "none", + examples: ["How does routing work in vercel/next.js?"], + toolEffects: { + read_wiki_structure: "read", + read_wiki_contents: "read", + ask_question: "read", + ask_wiki_question: "read", + }, + }, + { + id: "microsoft-learn", + title: "Microsoft Learn", + url: "https://learn.microsoft.com/api/mcp", + category: "Engineering", + description: "Official Microsoft and Azure docs. No sign-in.", + auth: "none", + examples: ["How do I rotate an Azure storage key?"], + }, + + // ── Data ───────────────────────────────────────────────────────────────── + { + id: "airtable", + title: "Airtable", + url: "https://mcp.airtable.com/mcp", + category: "Data", + description: "Bases, tables and records.", + auth: "oauth", + examples: ["Summarise the records added to my Airtable this week"], + }, + { + id: "posthog", + title: "PostHog", + url: "https://mcp.posthog.com/mcp", + category: "Data", + description: "Product analytics, feature flags and insights.", + auth: "oauth", + examples: ["How did signups trend this week?"], + }, + { + id: "amplitude", + title: "Amplitude", + url: "https://mcp.amplitude.com/mcp", + category: "Data", + description: "Charts, dashboards and user behaviour.", + auth: "oauth", + examples: ["Which features were used most last week?"], + }, + + // ── Research ───────────────────────────────────────────────────────────── + { + id: "exa", + title: "Exa", + url: "https://mcp.exa.ai/mcp", + category: "Research", + description: "Web search built for agents. No sign-in.", + auth: "none", + examples: ["Find recent articles about our competitors"], + }, + { + id: "tavily", + title: "Tavily", + url: "https://mcp.tavily.com/mcp", + category: "Research", + description: "Web search and page extraction.", + auth: "oauth", + examples: ["Research the pricing of the top three CRMs"], + }, + { + id: "apify", + title: "Apify", + url: "https://mcp.apify.com", + category: "Research", + description: "Ready-made scrapers for thousands of sites.", + auth: "oauth", + examples: ["Get the latest reviews of our product"], + }, + { + id: "huggingface", + title: "Hugging Face", + url: "https://huggingface.co/mcp", + category: "Research", + description: "Search models, datasets, papers and Spaces. No sign-in.", + auth: "none", + examples: ["Find a small open model for summarising text"], + }, +]; + +/** Same server despite cosmetic differences: case of the host, a trailing slash. */ +export function sameServer(a: string, b: string): boolean { + const norm = (u: string) => { + try { + const url = new URL(u); + return `${url.protocol}//${url.host.toLowerCase()}${url.pathname.replace(/\/+$/, "")}${url.search}`; + } catch { + return u; + } + }; + return norm(a) === norm(b); +} + +export function catalogAppFor(url: string): CatalogApp | undefined { + return CATALOG.find((a) => sameServer(a.url, url)); +} diff --git a/apps/server/src/routes/connections.ts b/apps/server/src/routes/connections.ts index 5f1ee6f..4a1b6d5 100644 --- a/apps/server/src/routes/connections.ts +++ b/apps/server/src/routes/connections.ts @@ -1,48 +1,48 @@ +import type { Effect as ToolEffect } from "@synapse/core"; import { schema } from "@synapse/db"; import { assertPublicUrl, clientMetadata, effectFromAnnotations, McpSession } from "@synapse/tools"; import { and, asc, eq } from "drizzle-orm"; import { Hono } from "hono"; import { z } from "zod"; +import { APP_CATEGORIES, CATALOG, catalogAppFor, sameServer } from "../catalog"; import { type AppEnv, apiError, body } from "../http"; const Effect = z.enum(["read", "write", "send", "destructive"]); -/** Well-known remote MCP servers. Users can add any other URL. */ -export const PRESETS = [ - { - name: "github", - url: "https://api.githubcopilot.com/mcp/", - description: "Repositories, issues, pull requests", - docs: "https://github.com/github/github-mcp-server", - }, - { - name: "linear", - url: "https://mcp.linear.app/mcp", - description: "Issues, projects, cycles", - docs: "https://linear.app/docs/mcp", - }, - { - name: "notion", - url: "https://mcp.notion.com/mcp", - description: "Pages and databases", - docs: "https://developers.notion.com/docs/mcp", - }, - { - name: "atlassian", - url: "https://mcp.atlassian.com/v1/mcp", - description: "Jira and Confluence", - docs: "https://support.atlassian.com/rovo/docs/getting-started-with-the-atlassian-remote-mcp-server/", - }, - { - name: "sentry", - url: "https://mcp.sentry.dev/mcp", - description: "Errors and issues", - docs: "https://docs.sentry.io/product/sentry-mcp/", - }, -]; - export const connections = new Hono() - .get("/presets", (c) => c.json({ presets: PRESETS })) + .get("/catalog", async (c) => { + const rows = await c.var.services.database.db + .select({ id: schema.connections.id, url: schema.connections.url }) + .from(schema.connections) + .where(eq(schema.connections.userId, c.var.user.id)); + return c.json({ + categories: APP_CATEGORIES, + apps: CATALOG.map((app) => ({ + ...app, + connectionId: rows.find((r) => sameServer(r.url, app.url))?.id ?? null, + })), + }); + }) + + /** One-click connect: the server and its name come from the directory, not the request. */ + .post("/catalog/:id", async (c) => { + const app = CATALOG.find((a) => a.id === c.req.param("id")); + if (!app) apiError(404, "not_found", "That app isn't in the directory."); + const { db } = c.var.services.database; + const mine = await db + .select({ name: schema.connections.name, url: schema.connections.url }) + .from(schema.connections) + .where(eq(schema.connections.userId, c.var.user.id)); + if (mine.some((r) => sameServer(r.url, app.url))) + apiError(409, "conflict", `${app.title} is already connected.`); + const taken = new Set(mine.map((r) => r.name)); + let name = app.id; + for (let i = 2; taken.has(name); i++) name = `${app.id}-${i}`; + return c.json( + await createConnection(c, { name, url: app.url, toolEffects: app.toolEffects }), + 201, + ); + }) .get("/", async (c) => { const { db } = c.var.services.database; @@ -72,9 +72,12 @@ export const connections = new Hono() effect: effectFromAnnotations(t, r.toolEffects), })) ?? null; } + const app = catalogAppFor(r.url); return { id: r.id, name: r.name, + title: app?.title ?? null, + examples: app?.examples ?? [], url: r.url, status: r.status, authType: r.auth.type, @@ -103,13 +106,7 @@ export const connections = new Hono() token: z.string().min(1).max(4000).optional(), }), ); - try { - await assertPublicUrl(input.url); - } catch (error) { - apiError(422, "blocked_url", error instanceof Error ? error.message : "URL not allowed"); - } const { db } = c.var.services.database; - const box = c.var.services.box; const [existing] = await db .select({ id: schema.connections.id }) .from(schema.connections) @@ -117,35 +114,7 @@ export const connections = new Hono() and(eq(schema.connections.userId, c.var.user.id), eq(schema.connections.name, input.name)), ); if (existing) apiError(409, "conflict", `A connection named "${input.name}" already exists.`); - - const [conn] = await db - .insert(schema.connections) - .values({ - userId: c.var.user.id, - name: input.name, - url: input.url, - status: "needs_auth", - auth: input.token - ? { type: "bearer", secret: await box.seal(input.token) } - : { type: "none" }, - }) - .returning(); - const session = new McpSession(db, box, c.var.services.toolset.app); - const result = await session.check(conn!); - await session.close(); - return c.json( - { - connection: { - id: conn!.id, - name: conn!.name, - url: conn!.url, - status: result.status, - lastError: result.error ?? null, - }, - ...(result.authorizationUrl ? { authorizationUrl: result.authorizationUrl } : {}), - }, - 201, - ); + return c.json(await createConnection(c, input), 201); }) .post("/:id/check", async (c) => { @@ -233,6 +202,46 @@ export function clientMetadataDocument(c: { var: AppEnv["Variables"] }) { return clientMetadata(c.var.services.toolset.app); } +/** Saves the connection, then tries it: active, or the URL to sign in at. */ +async function createConnection( + c: { var: AppEnv["Variables"] }, + input: { name: string; url: string; token?: string; toolEffects?: Record }, +) { + try { + await assertPublicUrl(input.url); + } catch (error) { + apiError(422, "blocked_url", error instanceof Error ? error.message : "URL not allowed"); + } + const { db } = c.var.services.database; + const box = c.var.services.box; + const [conn] = await db + .insert(schema.connections) + .values({ + userId: c.var.user.id, + name: input.name, + url: input.url, + status: "needs_auth", + auth: input.token + ? { type: "bearer", secret: await box.seal(input.token) } + : { type: "none" }, + ...(input.toolEffects ? { toolEffects: input.toolEffects } : {}), + }) + .returning(); + const session = new McpSession(db, box, c.var.services.toolset.app); + const result = await session.check(conn!); + await session.close(); + return { + connection: { + id: conn!.id, + name: conn!.name, + url: conn!.url, + status: result.status, + lastError: result.error ?? null, + }, + ...(result.authorizationUrl ? { authorizationUrl: result.authorizationUrl } : {}), + }; +} + async function ownConnection(c: { var: AppEnv["Variables"] }, id: string) { const [conn] = await c.var.services.database.db .select() diff --git a/apps/web/app/(app)/automations/page.tsx b/apps/web/app/(app)/automations/page.tsx index 2cf00b7..a70a715 100644 --- a/apps/web/app/(app)/automations/page.tsx +++ b/apps/web/app/(app)/automations/page.tsx @@ -1084,10 +1084,7 @@ function TemplateCard({ blocked ? ( Needs Google on this server ) : ( - + Connect {REQUIREMENT_NAMES[missing]} ) diff --git a/apps/web/app/(app)/connections/directory.tsx b/apps/web/app/(app)/connections/directory.tsx new file mode 100644 index 0000000..261825b --- /dev/null +++ b/apps/web/app/(app)/connections/directory.tsx @@ -0,0 +1,201 @@ +"use client"; + +import { Check, LoaderCircle, Search } from "lucide-react"; +import { useMemo, useState } from "react"; +import { useToast } from "@/components/toast"; +import { ErrorNote, Monogram, Pill, Skeleton } from "@/components/ui"; +import { api, type CatalogApp, errorMessage } from "@/lib/api"; +import { cx } from "@/lib/format"; +import { useApi } from "@/lib/use-api"; + +/** + * Apps that connect in one click: pick one, sign in on its site, and its tools show up under + * your approval rules. Search matches the name, the description and the example asks. + */ +export function AppDirectory({ + version, + onOpen, + onConnected, + onAuthorize, +}: { + /** Bumped when connections change elsewhere, so "Connected" stays right. */ + version: number; + onOpen: (connectionId: string) => void; + onConnected: () => void; + onAuthorize: (url: string) => void; +}) { + const toast = useToast(); + // Refetch when connections change, so "Connected" stays right. + const data = useApi(() => api.catalog(), String(version)); + const [query, setQuery] = useState(""); + const [category, setCategory] = useState(null); + const [busy, setBusy] = useState(null); + + const apps = data.data?.apps; + const categories = data.data?.categories ?? []; + const shown = useMemo(() => { + const q = query.trim().toLowerCase(); + return (apps ?? []).filter( + (a) => + (category === null || a.category === category) && + (!q || + [a.title, a.description, a.category, ...a.examples].some((s) => + s.toLowerCase().includes(q), + )), + ); + }, [apps, query, category]); + + async function connect(app: CatalogApp) { + setBusy(app.id); + try { + const res = await api.connectApp(app.id); + if (res.authorizationUrl) { + toast(`Taking you to ${app.title} to sign in…`); + onAuthorize(res.authorizationUrl); + return; + } + if (res.connection.status === "active") toast(`${app.title} connected`, "success"); + else toast(res.connection.lastError ?? `Couldn't reach ${app.title} yet`, "error"); + onConnected(); + await data.reload(); + } catch (err) { + toast(errorMessage(err), "error"); + } + setBusy(null); + } + + return ( +
+
+
+

+ App directory +

+

+ Connect in one click and sign in on the app's own site. Anything that sends, changes or + deletes still waits for your OK. +

+
+ +
+ + {data.error ? {errorMessage(data.error)} : null} + {!apps ? ( +
+ {[0, 1, 2, 3, 4, 5].map((i) => ( + + ))} +
+ ) : ( + <> +
+ {[null, ...categories].map((c) => { + const on = category === c; + return ( + + ); + })} +
+ {shown.length === 0 ? ( +

+ No app{category ? ` in ${category}` : ""} matches “{query.trim()}”. Any other MCP + server works too: use Add custom server. +

+ ) : ( +
    + {shown.map((app) => ( +
  • + void connect(app)} + onOpen={() => app.connectionId && onOpen(app.connectionId)} + /> +
  • + ))} +
+ )} + + )} +
+ ); +} + +function AppCard({ + app, + busy, + disabled, + onConnect, + onOpen, +}: { + app: CatalogApp; + busy: boolean; + disabled: boolean; + onConnect: () => void; + onOpen: () => void; +}) { + const connected = app.connectionId !== null; + return ( +
+
+ +
+

{app.title}

+

+ {app.category} +

+
+ {app.auth === "none" ? No sign-in : null} +
+

{app.description}

+ {app.examples[0] ? ( +

“{app.examples[0]}”

+ ) : ( + + )} +
+ {connected ? ( + + ) : ( + + )} +
+
+ ); +} diff --git a/apps/web/app/(app)/connections/page.tsx b/apps/web/app/(app)/connections/page.tsx index 2b67569..e30ef6f 100644 --- a/apps/web/app/(app)/connections/page.tsx +++ b/apps/web/app/(app)/connections/page.tsx @@ -18,10 +18,8 @@ import { LinearCard } from "@/components/linear-card"; import { Sheet } from "@/components/overlay"; import { useToast } from "@/components/toast"; import { - BrandGlyph, EFFECT_EXPLAINER, EffectPill, - EmptyState, ErrorNote, Field, Monogram, @@ -38,11 +36,11 @@ import { type ConnectionStatus, errorMessage, type GoogleIntegration, - type Preset, type SlackIntegration, } from "@/lib/api"; import { hostOf, humanize } from "@/lib/format"; import { useApi } from "@/lib/use-api"; +import { AppDirectory } from "./directory"; import { GitHubCard } from "./github-card"; const EFFECTS: Effect[] = ["read", "write", "send", "destructive"]; @@ -73,10 +71,15 @@ export default function ConnectionsPage() { const router = useRouter(); const toast = useToast(); const conns = useApi(() => api.connections()); - const presets = useApi(() => api.presets()); const integrations = useApi(() => api.integrations()); const [adding, setAdding] = useState(false); const [openId, setOpenId] = useState(null); + // Bumped whenever connections change, so the directory's "Connected" marks follow. + const [version, setVersion] = useState(0); + const changed = () => { + setVersion((v) => v + 1); + return conns.reload(); + }; // Result of an OAuth round-trip. // biome-ignore lint/correctness/useExhaustiveDependencies: once on mount @@ -90,7 +93,12 @@ export default function ConnectionsPage() { else if (connected === "linear") toast("Linear connected", "success"); else if (connected) toast("Connection authorized", "success"); if (error) toast(error.includes(" ") ? error : `Authorization failed: ${error}`, "error"); - if (q.has("add")) setAdding(true); + // "Add a connection" links land on the directory. + if (q.has("add")) + setTimeout(() => { + document.getElementById("directory-title")?.scrollIntoView({ behavior: "smooth" }); + document.getElementById("directory-search")?.focus({ preventScroll: true }); + }, 300); if (connected || error || q.has("add")) router.replace("/connections"); }, []); @@ -110,7 +118,7 @@ export default function ConnectionsPage() { } toast(`Connected ${res.connection.name}`, "success"); setAdding(false); - await conns.reload(); + await changed(); } return ( @@ -118,11 +126,11 @@ export default function ConnectionsPage() { setAdding(true)}> + } /> @@ -154,63 +162,58 @@ export default function ConnectionsPage() { )} -

MCP servers

{conns.error ? {errorMessage(conns.error)} : null} - {!list ? ( -
- {[0, 1, 2].map((i) => ( - - ))} -
- ) : list.length === 0 ? ( - } - title="No connections yet" - action={ - - } - > - Connect GitHub, Linear or any MCP server, and the agent can work inside it. - - ) : ( -
    - {list.map((c) => ( -
  • - -
  • - ))} -
- )} +
+ + + {c.tools ? `${c.tools.length} tools` : "Tools not loaded"} + +
+ + + ))} + + + ) : !list && !conns.error ? ( + + ) : null} + + void conns.reload()} + onAuthorize={startOAuth} + /> setOpenId(null)} - title={open ? humanizeName(open.name) : ""} + title={open ? displayName(open) : ""} description={open ? (hostOf(open.url) ?? open.url) : undefined} width={560} > @@ -220,20 +223,15 @@ export default function ConnectionsPage() { onChange={replace} onRemoved={() => { setOpenId(null); - void conns.reload(); + void changed(); }} onReload={() => void conns.reload()} /> ) : null} - setAdding(false)} title="Add a connection" width={600}> - !(list ?? []).some((c) => c.url === p.url), - )} - onAdd={add} - /> + setAdding(false)} title="Add a custom server" width={600}> + ); @@ -252,6 +250,9 @@ function humanizeName(name: string) { return name.length <= 3 ? name.toUpperCase() : name[0]!.toUpperCase() + name.slice(1); } +/** The directory's name for it ("Jira & Confluence"), else its own name, tidied. */ +const displayName = (c: Connection): string => c.title ?? humanizeName(c.name); + function ConnectionDetail({ connection: c, onChange, @@ -282,7 +283,7 @@ function ConnectionDetail({ const res = await api.checkConnection(c.id); if (res.authorizationUrl && authorize) return startOAuth(res.authorizationUrl); if (res.error) toast(res.error, "error"); - else if (res.status === "active") toast(`${humanizeName(c.name)} is working`, "success"); + else if (res.status === "active") toast(`${displayName(c)} is working`, "success"); else if (res.status === "needs_auth") toast("This connection needs authorization", "info"); onReload(); }); @@ -307,9 +308,7 @@ function ConnectionDetail({ {c.status === "needs_auth" ? (
-

- Authorize {humanizeName(c.name)} so the agent can use it. -

+

Authorize {displayName(c)} so the agent can use it.

You'll sign in on their site, then come back here.

@@ -431,11 +430,7 @@ function ConnectionDetail({ className="btn btn-danger" disabled={busy !== null} onClick={() => { - if ( - !window.confirm( - `Remove ${humanizeName(c.name)}? The agent loses access to its tools.`, - ) - ) + if (!window.confirm(`Remove ${displayName(c)}? The agent loses access to its tools.`)) return; void act("delete", async () => { await api.deleteConnection(c.id); @@ -452,95 +447,39 @@ function ConnectionDetail({ } function AddConnection({ - presets, onAdd, }: { - presets: Preset[]; onAdd: (b: { name: string; url: string; token?: string }) => Promise; }) { - const toast = useToast(); const [name, setName] = useState(""); const [url, setUrl] = useState(""); const [token, setToken] = useState(""); - const [busy, setBusy] = useState(null); + const [busy, setBusy] = useState(false); const [error, setError] = useState(null); - async function run(key: string, body: { name: string; url: string; token?: string }) { - setBusy(key); + async function submit(e: FormEvent) { + e.preventDefault(); + setBusy(true); setError(null); try { - await onAdd(body); + await onAdd({ + name: name.trim(), + url: url.trim(), + ...(token.trim() ? { token: token.trim() } : {}), + }); } catch (err) { - if (key === "custom") setError(errorMessage(err)); - else toast(errorMessage(err), "error"); + setError(errorMessage(err)); } finally { - setBusy(null); + setBusy(false); } } - function submit(e: FormEvent) { - e.preventDefault(); - void run("custom", { - name: name.trim(), - url: url.trim(), - ...(token.trim() ? { token: token.trim() } : {}), - }); - } - return (
- {presets.length > 0 ? ( -
-

Popular servers

-
    - {presets.map((p) => ( -
  • -
    -
    - -
    -
    - {humanizeName(p.name)} -
    -
    {hostOf(p.url)}
    -
    - -
    -

    {p.description}

    - {p.docs ? ( - - Docs · {hostOf(p.docs)} - - ) : null} -
    -
  • - ))} -
-
- ) : null} -
-

Custom server

-

- Any remote MCP server (Streamable HTTP). OAuth is detected automatically. +

+ Any remote MCP server (Streamable HTTP) that isn't in the app directory. OAuth is detected + automatically; for servers that use API keys, paste one as the bearer token.

@@ -581,8 +520,8 @@ function AddConnection({ /> {error ? {error} : null} - @@ -591,57 +530,6 @@ function AddConnection({ ); } -/** Empty-state art: three tools wired into the agent with dotted lines. */ -function SampleConnections() { - const tools = [ - { name: "GitHub", y: 34, note: "read" }, - { name: "Linear", y: 100, note: "write" }, - { name: "Notion", y: 166, note: "read" }, - ]; - return ( -
- - {tools.map((t, i) => ( -
- - - - {t.name} - - - {t.note} - - -
- ))} -
- -
-
- ); -} - /** "Drive", "Drive and Sheets", "Drive, Contacts and Sheets". */ const andList = (items: string[]) => items.length > 1 ? `${items.slice(0, -1).join(", ")} and ${items.at(-1)}` : (items[0] ?? ""); diff --git a/apps/web/app/(app)/page.tsx b/apps/web/app/(app)/page.tsx index c587872..708bb54 100644 --- a/apps/web/app/(app)/page.tsx +++ b/apps/web/app/(app)/page.tsx @@ -60,10 +60,15 @@ function suggestionsFor(conns: Connection[] | undefined): string[] { const out: string[] = []; for (const c of conns ?? []) { if (c.status !== "active") continue; + // Directory apps bring their own starter asks; one each, so several apps all get a turn. + if (c.examples[0]) { + out.push(c.examples[0]); + continue; + } const key = Object.keys(SUGGESTIONS).find((k) => c.name.toLowerCase().includes(k)); if (key) out.push(...SUGGESTIONS[key]!); } - return [...out, ...GENERAL].slice(0, 4); + return [...new Set([...out, ...GENERAL])].slice(0, 4); } const GUIDE_HIDDEN_KEY = "synapse-guide-hidden"; @@ -491,7 +496,7 @@ function FirstRunGuide({ case "tool": return { title: "Connect a tool", - body: "GitHub, Linear, Notion or any MCP server. The agent works inside them.", + body: "Notion, Jira, Stripe and dozens more in one click, or any MCP server. The agent works inside them.", art: (
{["GitHub", "Linear", "Notion"].map((n, i) => ( @@ -508,7 +513,7 @@ function FirstRunGuide({ action: done ? ( Connected ) : ( - Add a connection + Browse the app directory ), }; case "style": diff --git a/apps/web/lib/api.ts b/apps/web/lib/api.ts index 9089213..2309871 100644 --- a/apps/web/lib/api.ts +++ b/apps/web/lib/api.ts @@ -280,6 +280,10 @@ export type ConnectionStatus = "active" | "needs_auth" | "error" | "disabled" | export interface Connection { id: string; name: string; + /** Its name in the app directory, when it came from there. */ + title: string | null; + /** Things to ask it, from the app directory. */ + examples: string[]; url: string; status: ConnectionStatus; authType: string; @@ -287,11 +291,17 @@ export interface Connection { tools: ConnectionTool[] | null; } -export interface Preset { - name: string; +/** An app in the directory: a remote MCP server that connects in one click. */ +export interface CatalogApp { + id: string; + title: string; url: string; + category: string; description: string; - docs: string; + auth: "oauth" | "none"; + examples: string[]; + /** Set when you've already connected it. */ + connectionId: string | null; } export interface Memory { @@ -581,7 +591,11 @@ export const api = { approvals: () => get<{ approvals: Approval[] }>("/api/approvals"), connections: () => get<{ connections: Connection[] }>("/api/connections"), - presets: () => get<{ presets: Preset[] }>("/api/connections/presets"), + catalog: () => get<{ categories: string[]; apps: CatalogApp[] }>("/api/connections/catalog"), + connectApp: (id: string) => + post<{ connection: Connection; authorizationUrl?: string }>( + `/api/connections/catalog/${enc(id)}`, + ), addConnection: (body: { name: string; url: string; token?: string }) => post<{ connection: Connection; authorizationUrl?: string }>("/api/connections", body), checkConnection: (id: string) => diff --git a/docs/api.md b/docs/api.md index 13d2579..e5af06c 100644 --- a/docs/api.md +++ b/docs/api.md @@ -78,13 +78,14 @@ Event types (`RunEvent` in `packages/core/src/types.ts`): `run.status`, `message | Method | Path | Body | Response | |---|---|---|---| -| GET | `/api/connections` | | `{ connections: { id, name, url, status, authType, lastError, tools: { name, title, description, effect }[] \| null }[] }` | +| GET | `/api/connections` | | `{ connections: { id, name, title, examples, url, status, authType, lastError, tools: { name, title, description, effect }[] \| null }[] }` — `title` and `examples` come from the app directory when the URL is one of its servers, else `null` and `[]` | | POST | `/api/connections` | `{ name, url, token?: string }` | `{ connection, authorizationUrl?: string }` — open `authorizationUrl` in the browser to finish OAuth | | POST | `/api/connections/:id/check` | | `{ status, authorizationUrl?, error? }` | | PATCH | `/api/connections/:id` | `{ toolEffects?: Record, status?: "active" \| "disabled" }` | `{ connection }` | | DELETE | `/api/connections/:id` | | `204` | | GET | `/api/connections/oauth/callback?code&state` | | redirects to `${WEB_URL}/connections?connected=` or `?error=…` | -| GET | `/api/connections/presets` | | `{ presets: { name, url, description, docs }[] }` — well-known remote MCP servers | +| GET | `/api/connections/catalog` | | `{ categories, apps: { id, title, url, category, description, auth: "oauth" \| "none", examples, connectionId }[] }` — the app directory; `connectionId` is set when you've connected that server | +| POST | `/api/connections/catalog/:id` | | `{ connection, authorizationUrl?: string }` — one-click connect: URL and name come from the directory. `409` if that server is already connected, `404` for an unknown id | ## Integrations (built in) diff --git a/docs/design.md b/docs/design.md index 3102722..857958f 100644 --- a/docs/design.md +++ b/docs/design.md @@ -149,7 +149,8 @@ Tabs **Documents** (drop zone, list, search with highlighted passages) and **Mem ### Connections `/connections` Grid of connection cards (monogram, name, URL host, status pill, tools count) → detail sheet listing tools with effect selector per tool and a short explainer of effects. -"Add connection" sheet: presets grid + custom URL/token form. OAuth "Authorize" flow and +App directory below: search, category chips, one-click Connect per app (starter ask quoted +on each card). "Add custom server" sheet: URL/token form. OAuth "Authorize" flow and `?connected=` / `?error=` toasts. ### Settings `/settings` diff --git a/docs/linear.md b/docs/linear.md index 59ad214..6667f93 100644 --- a/docs/linear.md +++ b/docs/linear.md @@ -8,7 +8,7 @@ their own Linear from **Connections → Linear**. Tokens are encrypted with `SYNAPSE_SECRET` and never leave your server. Disconnecting revokes them at Linear and deletes them. -Prefer Linear's hosted MCP server? It is still in the **Add connection** presets. The built-in +Prefer Linear's hosted MCP server? It is in the **App directory** on the Connections page. The built-in tools add tailored approval cards, plain-language risk facts and the "a read never widens the write" check on teams and issues; you can use either, or both. diff --git a/packages/tools/src/mcp/client.ts b/packages/tools/src/mcp/client.ts index 39ee7df..63c2a91 100644 --- a/packages/tools/src/mcp/client.ts +++ b/packages/tools/src/mcp/client.ts @@ -93,13 +93,16 @@ export class McpSession { private readonly app: OAuthAppConfig, ) {} + private async provider(conn: Connection): Promise { + return conn.auth.type === "oauth" + ? ConnectionOAuthProvider.load(this.db, this.box, conn.id, this.app) + : null; + } + private async open( conn: Connection, + provider: ConnectionOAuthProvider | null, ): Promise<{ client: Client; provider: ConnectionOAuthProvider | null }> { - const provider = - conn.auth.type === "oauth" - ? await ConnectionOAuthProvider.load(this.db, this.box, conn.id, this.app) - : null; const headers: Record = {}; if (conn.auth.type === "bearer" && conn.auth.secret) headers.authorization = `Bearer ${await this.box.open(conn.auth.secret)}`; @@ -115,10 +118,10 @@ export class McpSession { /** Connects (or re-checks) a connection and records its status. Used by the connections API. */ async check(conn: Connection): Promise { - let provider: ConnectionOAuthProvider | null = null; + // Made before connecting: when the server wants a sign-in, the SDK leaves the URL on it. + const provider = await this.provider(conn); try { - const opened = await this.open(conn); - provider = opened.provider; + const opened = await this.open(conn, provider); const { tools } = await opened.client.listTools(); await opened.client.close(); await this.db @@ -207,7 +210,7 @@ export class McpSession { private async client(conn: Connection): Promise { let client = this.clients.get(conn.id); if (!client) { - client = (await this.open(conn)).client; + client = (await this.open(conn, await this.provider(conn))).client; this.clients.set(conn.id, client); } return client; diff --git a/packages/tools/src/tools.test.ts b/packages/tools/src/tools.test.ts index 037dd7e..220c8b9 100644 --- a/packages/tools/src/tools.test.ts +++ b/packages/tools/src/tools.test.ts @@ -2,6 +2,7 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test"; import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js"; import { createDatabase, type Database, SecretBox, schema } from "@synapse/db"; +import { eq } from "drizzle-orm"; import { z } from "zod"; import { extractText } from "./builtin/files"; import { chunkText, ingestDocument, searchKnowledge } from "./builtin/knowledge"; @@ -81,6 +82,37 @@ describe("with a database", () => { server = Bun.serve({ port: 0, fetch: async (req) => { + const path = new URL(req.url).pathname; + const origin = `http://127.0.0.1:${server.port}`; + // A server that wants OAuth, with dynamic client registration, at /oauth-mcp. + if (path === "/.well-known/oauth-protected-resource/oauth-mcp") + return Response.json({ + resource: `${origin}/oauth-mcp`, + authorization_servers: [origin], + }); + if (path === "/.well-known/oauth-authorization-server") + return Response.json({ + issuer: origin, + authorization_endpoint: `${origin}/authorize`, + token_endpoint: `${origin}/token`, + registration_endpoint: `${origin}/register`, + response_types_supported: ["code"], + code_challenge_methods_supported: ["S256"], + }); + if (path === "/register") + return Response.json( + { ...((await req.json()) as object), client_id: "registered-client" }, + { + status: 201, + }, + ); + if (path === "/oauth-mcp") + return new Response("unauthorized", { + status: 401, + headers: { + "www-authenticate": `Bearer resource_metadata="${origin}/.well-known/oauth-protected-resource/oauth-mcp"`, + }, + }); if (req.headers.get("authorization") !== "Bearer secret-token") return new Response("unauthorized", { status: 401 }); const mcp = new McpServer({ name: "test", version: "1.0.0" }); @@ -168,6 +200,39 @@ describe("with a database", () => { expect(result.status).not.toBe("active"); }); + test("a server that wants OAuth comes back with the URL to sign in at", async () => { + const box = await SecretBox.fromSecret("s".repeat(32)); + const [conn] = await database.db + .insert(schema.connections) + .values({ + userId: "u1", + name: "signin", + url: `http://127.0.0.1:${server.port}/oauth-mcp`, + status: "needs_auth", + auth: { type: "none" }, + }) + .returning(); + const session = new McpSession(database.db, box, { + publicUrl: "http://localhost:3000", + appName: "t", + }); + const result = await session.check(conn!); + expect(result.status).toBe("needs_auth"); + const url = new URL(result.authorizationUrl!); + expect(`${url.origin}${url.pathname}`).toBe(`http://127.0.0.1:${server.port}/authorize`); + expect(url.searchParams.get("client_id")).toBe("registered-client"); + expect(url.searchParams.get("code_challenge_method")).toBe("S256"); + expect(url.searchParams.get("redirect_uri")).toBe( + "http://localhost:3000/api/connections/oauth/callback", + ); + const [row] = await database.db + .select() + .from(schema.connections) + .where(eq(schema.connections.id, conn!.id)); + expect(row!.auth.type).toBe("oauth"); + await session.close(); + }); + test("knowledge search (full-text only) finds and ranks passages per user", async () => { await ingestDocument(database.db, null, { userId: "u1",