Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

fix(mcp): post to the configured MCP endpoint; list linked per-user MCP sign-ins (#2290)

Joshua France7ca4aea39d8c
diff --git a/plugins/web-ui/src/connectors.ts b/plugins/web-ui/src/connectors.ts
index 4d9f92d07..c71889fd9 100644
--- a/plugins/web-ui/src/connectors.ts
+++ b/plugins/web-ui/src/connectors.ts
@@ -11,6 +11,7 @@ import { isActiveGrant, isExpiredCredential, KeychainOperations } from "./keycha
import { listPageTpl } from "./list-page";
interface ConnectorProvider {
+ mcpLabel?: string;
connected?: boolean;
needsReconnect?: boolean;
refreshError?: string;
@@ -399,7 +400,7 @@ function drawConnectors(): void {
const loading = accountsLoading || keysLoadingFresh;
const entries = Object.entries(connectorProviders);
const connectorCards = entries.map(([id, p]) => {
- const meta = CONNECTOR_LABELS[id] ?? { name: id, hosts: "" };
+ const meta = CONNECTOR_LABELS[id] ?? { name: p.mcpLabel ?? id, hosts: "" };
const connected = Boolean(p.connected);
const needsReconnect = Boolean(p.needsReconnect);
const available = Boolean(p.available);
diff --git a/src/api/routes/connectors.ts b/src/api/routes/connectors.ts
index 35fd2d096..8d48eaf47 100644
--- a/src/api/routes/connectors.ts
+++ b/src/api/routes/connectors.ts
@@ -15,8 +15,8 @@ import {
type AccountType,
type OAuthState,
} from "../../connectors/oauth.ts";
-import { bestOAuthTokenStatus, CONNECTOR_STATUS_ACCOUNT_TYPES } from "../../credentials/connector-status.ts";
-import type { DerivedOAuthAuth, OAuthTokenStatus } from "../../credentials/keychain.ts";
+import { CONNECTOR_STATUS_ACCOUNT_TYPES, providerTokenStatuses } from "../../credentials/connector-status.ts";
+import type { ConnectorTokenStore, DerivedOAuthAuth, OAuthTokenStatus } from "../../credentials/keychain.ts";
import { createEnvSecretSource } from "../../credentials/secret-source.ts";
import type { ServerDeps } from "../deps.ts";
import { personKey, samePerson } from "../../directory/person.ts";
@@ -81,8 +81,6 @@ function safeReturnTo(value: string | null): string | undefined {
return value;
}
-type HostStatus = OAuthTokenStatus & { host: string };
-
function latestRefreshFailure(
entries: ReadonlyArray<Pick<OAuthTokenStatus, "refreshFailedAt" | "refreshError">>,
): Pick<OAuthTokenStatus, "refreshFailedAt" | "refreshError"> {
@@ -101,29 +99,20 @@ function latestRefreshFailure(
return latest;
}
-async function connectorProviderStatus(deps: ServerDeps, principalId: string): Promise<Record<string, unknown>> {
+async function connectorProviderStatus(
+ deps: ServerDeps,
+ tokens: ConnectorTokenStore,
+ principalId: string,
+): Promise<Record<string, unknown>> {
const entries = await Promise.all(
- Object.entries(PROVIDERS).map(async ([name, provider]) => {
- const [hosts, configured] = await Promise.all([
- Promise.all(
- provider.hosts.map(async (host) => {
- const probed = await Promise.all(
- CONNECTOR_STATUS_ACCOUNT_TYPES.map(
- async (at) =>
- (await deps.connectorTokens?.connectorTokenStatus(host, principalId, at)) ?? { connected: false },
- ),
- );
- const best = bestOAuthTokenStatus(probed);
- return { host, ...best };
- }),
- ) as Promise<HostStatus[]>,
- providerConfigured(deps, name),
- ]);
+ (await providerTokenStatuses(tokens, principalId)).map(async ({ name, provider, hosts }) => {
+ const configured = await providerConfigured(deps, name);
const reconnectHosts = hosts.filter((h) => h.needsReconnect);
const latestFailure = latestRefreshFailure(hosts);
return [
name,
{
+ ...(provider.mcpLabel ? { mcpLabel: provider.mcpLabel } : {}),
hosts,
connected: hosts.some((h) => h.connected && !h.needsReconnect),
...(reconnectHosts.length ? { needsReconnect: true } : {}),
@@ -421,7 +410,10 @@ async function oauthStatus(ctx: ApiCtx): Promise<void> {
const principalId = url.searchParams.get("principalId") ?? "";
if (!principalId) return sendJson(res, 400, { error: "bad_request", message: "principalId required" });
audit(deps, { principalId, action: "connector.oauth.status", resource: "connectors", scopeLabel: principalId });
- return sendJson(res, 200, { principalId, providers: await connectorProviderStatus(deps, principalId) });
+ return sendJson(res, 200, {
+ principalId,
+ providers: await connectorProviderStatus(deps, deps.connectorTokens, principalId),
+ });
}
export async function oauthRevoke(ctx: ApiCtx): Promise<void> {
diff --git a/src/connectors/oauth.ts b/src/connectors/oauth.ts
index b48599238..00383c9ff 100644
--- a/src/connectors/oauth.ts
+++ b/src/connectors/oauth.ts
@@ -53,6 +53,7 @@ export interface OAuthProviderConfig {
exchange?: OAuthExchangeAdapter;
refresh?: OAuthRefreshAdapter | null;
pkce?: boolean;
+ mcpLabel?: string;
}
export type FetchLike = (
@@ -455,6 +456,7 @@ export interface PublicOAuthClient {
scopes: string[];
clientId: string;
resource?: string;
+ label: string;
}
const publicClients = new Map<string, PublicOAuthClient>();
@@ -477,12 +479,17 @@ export function setPublicOAuthClients(clients: PublicOAuthClient[]): void {
consentMode: "standard",
egressRule: [],
pkce: true,
+ mcpLabel: c.label,
...(c.resource ? { authParams: { resource: c.resource } } : {}),
setupGuide: { console: "Admin → MCP servers", url: "", steps: [] },
});
}
}
+export function oauthProviderEntries(): Array<[string, OAuthProviderConfig]> {
+ return [...Object.entries(PROVIDERS), ...publicProviders.entries()];
+}
+
export function oauthProvider(name: string): OAuthProviderConfig | undefined {
return PROVIDERS[name] ?? publicProviders.get(name);
}
diff --git a/src/core/environment-facts.ts b/src/core/environment-facts.ts
index 1849c432e..ac40085ad 100644
--- a/src/core/environment-facts.ts
+++ b/src/core/environment-facts.ts
@@ -45,28 +45,30 @@ export function renderConnectedAppsBlock(
): string {
const allowed = new Set(availableProviders);
const entries = Object.entries(record?.providers ?? {})
- .filter(([name]) => allowed.has(name))
+ .filter(([name, e]) => allowed.has(name) || e.mcpLabel)
.sort(([a], [b]) => a.localeCompare(b));
- const connected = entries.filter(([, e]) => e.connected && !e.needsReconnect).map(([name]) => connectorLabel(name));
+ const label = (name: string, e: (typeof entries)[number][1]) => e.mcpLabel ?? connectorLabel(name);
+ const connected = entries.filter(([, e]) => e.connected && !e.needsReconnect).map(([name, e]) => label(name, e));
const reconnect = entries
.filter(([, e]) => e.needsReconnect)
- .map(([name, e]) => `${connectorLabel(name)}${e.refreshError ? ` (refresh failed: ${e.refreshError})` : ""}`);
+ .map(([name, e]) => `${label(name, e)}${e.refreshError ? ` (refresh failed: ${e.refreshError})` : ""}`);
const lines = [
"## Connected apps",
"This list covers direct OAuth only; it does not describe app access through separately authorized credentials. Use the matching access skill for those, respecting explicit app restrictions and account permissions.",
];
if (!availableProviders.length) {
lines.push("No direct OAuth app connections are configured. Do not offer direct OAuth consent links.");
- return lines.join("\n");
- }
- const connectedNames = new Set(entries.filter(([, e]) => e.connected).map(([name]) => name));
- const available = availableProviders.filter((name) => !connectedNames.has(name)).sort();
- if (available.length) {
- lines.push(
- `Available to connect: ${available.map(connectorLabel).join(", ")}. Only offer direct OAuth consent links for this admin-configured list.`,
- );
+ if (!connected.length && !reconnect.length) return lines.join("\n");
} else {
- lines.push("Only offer direct OAuth consent links for the admin-configured list below.");
+ const connectedNames = new Set(entries.filter(([, e]) => e.connected).map(([name]) => name));
+ const available = availableProviders.filter((name) => !connectedNames.has(name)).sort();
+ if (available.length) {
+ lines.push(
+ `Available to connect: ${available.map(connectorLabel).join(", ")}. Only offer direct OAuth consent links for this admin-configured list.`,
+ );
+ } else {
+ lines.push("Only offer direct OAuth consent links for the admin-configured list below.");
+ }
}
if (connectionsUrl) lines.push(`Connection page: ${connectionsUrl}`);
if (connected.length) {
diff --git a/src/credentials/connector-status.ts b/src/credentials/connector-status.ts
index 5effbeaad..fb6d21b1a 100644
--- a/src/credentials/connector-status.ts
+++ b/src/credentials/connector-status.ts
@@ -1,9 +1,15 @@
import type { DurableMap } from "../persistence/durable-map.ts";
import type { ConnectorTokenStore, OAuthTokenStatus } from "./keychain.ts";
-import { PROVIDERS, type OAuthClientResolver } from "../connectors/oauth.ts";
+import {
+ oauthProviderEntries,
+ PROVIDERS,
+ type OAuthClientResolver,
+ type OAuthProviderConfig,
+} from "../connectors/oauth.ts";
interface ConnectorStatusEntry {
connected: boolean;
+ mcpLabel?: string;
expiresAt?: number;
needsReconnect?: boolean;
refreshFailedAt?: number;
@@ -47,7 +53,7 @@ export function connectorStatusIsStale(
return false;
}
-export function bestOAuthTokenStatus(statuses: readonly OAuthTokenStatus[]): OAuthTokenStatus {
+function bestOAuthTokenStatus(statuses: readonly OAuthTokenStatus[]): OAuthTokenStatus {
return (
statuses.find((s) => s.connected && !s.needsReconnect) ??
statuses.find((s) => s.connected) ??
@@ -72,23 +78,39 @@ function mergeStatus(entry: ConnectorStatusEntry, status: OAuthTokenStatus): Con
return next;
}
+export type HostTokenStatus = OAuthTokenStatus & { host: string };
+
+export async function providerTokenStatuses(
+ tokens: ConnectorTokenStore,
+ principalId: string,
+): Promise<Array<{ name: string; provider: OAuthProviderConfig; hosts: HostTokenStatus[] }>> {
+ const all = await Promise.all(
+ oauthProviderEntries().map(async ([name, provider]) => {
+ const hosts = await Promise.all(
+ provider.hosts.map(async (host) => {
+ const statuses = await Promise.all(
+ CONNECTOR_STATUS_ACCOUNT_TYPES.map((accountType) =>
+ tokens.connectorTokenStatus(host, principalId, accountType),
+ ),
+ );
+ return { host, ...bestOAuthTokenStatus(statuses) };
+ }),
+ );
+ return { name, provider, hosts };
+ }),
+ );
+ return all.filter(({ provider, hosts }) => !provider.mcpLabel || hosts.some((h) => h.connected));
+}
+
export async function refreshConnectorStatus(
tokens: ConnectorTokenStore,
principalId: string,
now: number,
): Promise<ConnectorStatusRecord> {
const providers: Record<string, ConnectorStatusEntry> = {};
- for (const [name, provider] of Object.entries(PROVIDERS)) {
- let entry: ConnectorStatusEntry = { connected: false };
- for (const host of provider.hosts) {
- const statuses = await Promise.all(
- CONNECTOR_STATUS_ACCOUNT_TYPES.map((accountType) =>
- tokens.connectorTokenStatus(host, principalId, accountType),
- ),
- );
- entry = mergeStatus(entry, bestOAuthTokenStatus(statuses));
- }
- providers[name] = entry;
+ for (const { name, provider, hosts } of await providerTokenStatuses(tokens, principalId)) {
+ const entry = hosts.reduce<ConnectorStatusEntry>((acc, status) => mergeStatus(acc, status), { connected: false });
+ providers[name] = provider.mcpLabel ? { ...entry, mcpLabel: provider.mcpLabel } : entry;
}
return { principalId, checkedAt: now, providers };
}
diff --git a/src/mcp/mcp-client.ts b/src/mcp/mcp-client.ts
index 96f178be3..398193218 100644
--- a/src/mcp/mcp-client.ts
+++ b/src/mcp/mcp-client.ts
@@ -26,8 +26,9 @@ export type McpFetch = (
const realFetch: McpFetch = (url, init) => fetch(url, { ...init, redirect: "error" });
-function baseUrl(mcpUrl: string): string {
- return mcpUrl.replace(/\/+$/g, "").replace(/\/mcp$/g, "");
+function endpointUrl(mcpUrl: string): string {
+ const trimmed = mcpUrl.replace(/\/+$/g, "");
+ return new URL(trimmed).pathname === "/" ? `${trimmed}/mcp` : trimmed;
}
function hostOf(base: string): string {
@@ -127,7 +128,8 @@ export function createMcpClient(opts: {
}): McpClient {
const fetchImpl = opts.fetchImpl ?? realFetch;
const now = opts.now ?? (() => Date.now());
- const base = baseUrl(opts.url);
+ const endpoint = endpointUrl(opts.url);
+ const base = endpoint.replace(/\/mcp$/g, "");
const host = hostOf(base);
let cached: CachedToken | null = null;
let rpcId = 0;
@@ -161,7 +163,7 @@ export function createMcpClient(opts: {
async function rpc(method: string, params: Record<string, unknown>): Promise<unknown> {
const id = ++rpcId;
- const res = await fetchImpl(`${base}/mcp`, {
+ const res = await fetchImpl(endpoint, {
method: "POST",
headers: {
...(await authHeaders()),
diff --git a/src/mcp/mcp-tool-service.ts b/src/mcp/mcp-tool-service.ts
index f88ee1a06..b9f3c810d 100644
--- a/src/mcp/mcp-tool-service.ts
+++ b/src/mcp/mcp-tool-service.ts
@@ -29,6 +29,7 @@ export function mcpPublicOAuthClients(servers: McpServer[]): PublicOAuthClient[]
scopes: s.oauthScopes ?? [],
clientId: s.clientId,
resource: s.url,
+ label: s.name,
},
]
: [],
diff --git a/test/connector-status.test.ts b/test/connector-status.test.ts
index 306d15771..c98dc0da5 100644
--- a/test/connector-status.test.ts
+++ b/test/connector-status.test.ts
@@ -9,6 +9,7 @@ import {
type ConnectorStatusRecord,
} from "../src/credentials/connector-status.ts";
import type { ConnectorTokenStore, OAuthTokenStatus } from "../src/credentials/keychain.ts";
+import { setPublicOAuthClients } from "../src/connectors/oauth.ts";
function fakeTokens(status: (host: string, accountType?: string) => OAuthTokenStatus): ConnectorTokenStore {
return {
@@ -135,3 +136,24 @@ test("labels: known providers get friendly names; unknown is capitalized", () =>
assert.equal(connectorLabel("github"), "GitHub");
assert.equal(connectorLabel("acme"), "Acme");
});
+
+test("refresh includes linked per-user MCP sign-ins and skips unlinked ones", async (t) => {
+ t.after(() => setPublicOAuthClients([]));
+ const client = (name: string, label: string) => ({
+ name,
+ host: `api.${name}.example`,
+ authUrl: `https://id.${name}.example/authorize`,
+ tokenUrl: `https://id.${name}.example/token`,
+ scopes: [`${name}:write`],
+ clientId: "public-client",
+ label,
+ });
+ setPublicOAuthClients([client("orders", "Orders"), client("other", "Other")]);
+ const rec = await refreshConnectorStatus(
+ fakeTokens((host) => (host === "api.orders.example" ? { connected: true } : { connected: false })),
+ "U1",
+ 1,
+ );
+ assert.deepEqual(rec.providers.orders, { connected: true, mcpLabel: "Orders" });
+ assert.equal(rec.providers.other, undefined);
+});
diff --git a/test/environment-facts.test.ts b/test/environment-facts.test.ts
index 9c95c5732..33bd4df80 100644
--- a/test/environment-facts.test.ts
+++ b/test/environment-facts.test.ts
@@ -112,3 +112,22 @@ test("connected-apps block is canonical across provider and status insertion ord
);
assert.deepEqual(Object.keys(providers), ["slack", "google", "github", "dropbox"]);
});
+
+test("connected-apps block: names linked per-user MCP sign-ins by label", () => {
+ const rec: ConnectorStatusRecord = {
+ principalId: "U1",
+ checkedAt: 1,
+ providers: {
+ google: { connected: true },
+ orders: { connected: true, mcpLabel: "Orders" },
+ },
+ };
+ const out = renderConnectedAppsBlock(rec, ["google"], "https://qm.example/keychain");
+ assert.match(out, /Connected: Google, Orders\./);
+ assert.doesNotMatch(out, /Available to connect: .*Orders/);
+
+ const mcpOnly = renderConnectedAppsBlock(rec, [], "https://qm.example/keychain");
+ assert.match(mcpOnly, /No direct OAuth app connections are configured/);
+ assert.match(mcpOnly, /Connected: Orders\./);
+ assert.doesNotMatch(mcpOnly, /Google/);
+});
diff --git a/test/mcp-connectors.test.ts b/test/mcp-connectors.test.ts
index 45344f5c2..2815b0b4c 100644
--- a/test/mcp-connectors.test.ts
+++ b/test/mcp-connectors.test.ts
@@ -88,6 +88,47 @@ test("mcp client sends bearer auth", async () => {
await assert.rejects(() => bad.listTools(), /HTTP 401/);
});
+test("mcp client posts to the configured endpoint path", async () => {
+ const cases: Array<[string, string]> = [
+ ["https://api.example.com/mcp/consumer", "https://api.example.com/mcp/consumer"],
+ ["https://api.example.com/mcp/consumer/", "https://api.example.com/mcp/consumer"],
+ ["https://mcp.example.com/mcp", "https://mcp.example.com/mcp"],
+ ["https://mcp.example.com/mcp/", "https://mcp.example.com/mcp"],
+ ["https://mcp.example.com", "https://mcp.example.com/mcp"],
+ ["http://memory.internal:8080/", "http://memory.internal:8080/mcp"],
+ ];
+ for (const [url, expected] of cases) {
+ const seen: string[] = [];
+ const fetchImpl: McpFetch = async (target) => {
+ seen.push(target);
+ return {
+ ok: true,
+ status: 200,
+ text: async () => JSON.stringify({ jsonrpc: "2.0", id: 1, result: { tools: [] } }),
+ };
+ };
+ await createMcpClient({ url, auth: { mode: "none" }, fetchImpl }).listTools();
+ assert.deepEqual(seen, [expected], url);
+ }
+});
+
+test("mcp client mints client-credentials tokens beside the endpoint", async () => {
+ const seen: string[] = [];
+ const fetchImpl: McpFetch = async (target) => {
+ seen.push(target);
+ const body = target.endsWith("/token")
+ ? { access_token: "minted", expires_in: 3600 }
+ : { jsonrpc: "2.0", id: 1, result: { tools: [] } };
+ return { ok: true, status: 200, text: async () => JSON.stringify(body) };
+ };
+ await createMcpClient({
+ url: "https://mcp.example.com/mcp",
+ auth: { mode: "client-credentials", clientId: "id", clientSecret: "secret" },
+ fetchImpl,
+ }).listTools();
+ assert.deepEqual(seen, ["https://mcp.example.com/token", "https://mcp.example.com/mcp"]);
+});
+
test("server id validation", () => {
assert.ok(isValidMcpServerId("salesforce"));
assert.ok(isValidMcpServerId("crm-2"));
diff --git a/test/oauth-routes.test.ts b/test/oauth-routes.test.ts
index 6f0a1406a..812940526 100644
--- a/test/oauth-routes.test.ts
+++ b/test/oauth-routes.test.ts
@@ -9,7 +9,7 @@ import type { AddressInfo } from "node:net";
import { createServer } from "../src/api/server.ts";
import { buildApp, type BuiltApp } from "../src/wiring.ts";
import { signRequest } from "../src/auth/source-auth.ts";
-import { PROVIDERS, type FetchLike } from "../src/connectors/oauth.ts";
+import { PROVIDERS, setPublicOAuthClients, type FetchLike } from "../src/connectors/oauth.ts";
import { testConfig } from "./support/test-config.ts";
const SECRET = "oauth-route-test-secret".repeat(3);
@@ -241,3 +241,44 @@ test("authorize state stays inside the tightest provider limit and still carries
await srv.close();
}
});
+
+test("OAuth status lists a linked per-user MCP sign-in under its display name", async (t) => {
+ t.after(() => setPublicOAuthClients([]));
+ const srv = start(async () => {
+ throw new Error("no token exchange expected");
+ });
+ try {
+ await srv.built.mcpToolService.refresh();
+ setPublicOAuthClients([
+ {
+ name: "orders",
+ host: "api.orders.example",
+ authUrl: "https://id.orders.example/authorize",
+ tokenUrl: "https://id.orders.example/token",
+ scopes: ["orders:write"],
+ clientId: "public-client",
+ label: "Orders",
+ },
+ ]);
+ const statusPath = "/v1/connectors/oauth/status?principalId=U1";
+ const read = async () => {
+ const res = await fetch(`${srv.base}${statusPath}`, { headers: sign("GET", statusPath) });
+ assert.equal(res.status, 200);
+ return (await res.json()) as {
+ providers: Record<string, { connected?: boolean; mcpLabel?: string; available?: boolean }>;
+ };
+ };
+ assert.equal((await read()).providers.orders, undefined, "unlinked MCP sign-ins stay out of the list");
+
+ await srv.built.connectorTokens.setConnectorToken("api.orders.example", "U1", {
+ accessToken: "orders-token",
+ expiresAt: Date.now() + 3_600_000,
+ });
+ const linked = (await read()).providers.orders;
+ assert.equal(linked?.connected, true);
+ assert.equal(linked?.mcpLabel, "Orders");
+ assert.equal(linked?.available, true);
+ } finally {
+ await srv.close();
+ }
+});