Skip to content

Open source alternative to Semrush and Ahrefs

Make hosted MCP OAuth grants user-scoped across organizations (#610)

devin-ai-integration[bot]861d61e8aed7
diff --git a/src/server/mcp/api-key-auth.test.ts b/src/server/mcp/api-key-auth.test.ts
index fb74874d..15e9fb75 100644
--- a/src/server/mcp/api-key-auth.test.ts
+++ b/src/server/mcp/api-key-auth.test.ts
@@ -103,9 +103,6 @@ describe("handleMcpApiKeyRequest", () => {
userEmail: "[email protected]",
organizationId: "org-1",
role: "owner",
- // The key is user-scoped: project tools authorize per call via
- // membership in the project's org, not this request-level org.
- orgScope: "user",
scopes: [...MCP_OAUTH_SCOPES],
clientId: "api_key",
baseUrl: "https://app.openseo.so",
diff --git a/src/server/mcp/api-key-auth.ts b/src/server/mcp/api-key-auth.ts
index 171e1c17..6d774631 100644
--- a/src/server/mcp/api-key-auth.ts
+++ b/src/server/mcp/api-key-auth.ts
@@ -141,16 +141,14 @@ export async function handleMcpApiKeyRequest(
// clientId "api_key" satisfies the hosted transport's fail-closed props
// schema and counts these calls as external MCP clients in telemetry.
- // orgScope "user": the key itself is the credential, not a key→org
- // binding — project-scoped tools authorize per call via the caller's
- // membership in the project's org, and organizationId above is only the
- // fallback for tools with no project argument.
+ // The key is the credential, not a key→org binding: the hosted transport
+ // stamps orgScope "user", and organizationId above is only the fallback
+ // for tools with no project argument.
const props = createWorkersOAuthMcpProps({
userId,
userEmail: user.email,
organizationId,
role,
- orgScope: "user",
baseUrl: getHostedBaseUrl(),
scopes: [...MCP_OAUTH_SCOPES],
clientId: "api_key",
diff --git a/src/server/mcp/context.ts b/src/server/mcp/context.ts
index c5f7c330..2df60c8d 100644
--- a/src/server/mcp/context.ts
+++ b/src/server/mcp/context.ts
@@ -12,10 +12,11 @@ export type ToolAuthContext = {
// transport.ts. Self-host/delegated: one implicit user per org → "owner".
role: string;
// How tool calls bind to an organization. "pinned": the request's
- // organizationId is the authorization boundary — OAuth tokens (org stamped
- // at consent) and self-host. "user": the credential is user-scoped (API
- // keys) — project-scoped tools derive the org from the project row and
- // authorize via the caller's membership in THAT org, so one key works
+ // organizationId is the authorization boundary — self-host and SAM, which
+ // have no member rows or are already bound to one project. "user": every
+ // hosted credential (OAuth tokens, API keys; stamped by the hosted
+ // transport) — project-scoped tools derive the org from the project row and
+ // authorize via the caller's membership in THAT org, so one credential works
// across every organization the user belongs to; organizationId is only the
// fallback context for the few tools with no project argument.
orgScope: "pinned" | "user";
@@ -42,7 +43,8 @@ const applicationAuthContextSchema = z.object({
// transport, never baked into tokens) and from delegated modes (implicit
// owner).
role: z.string().min(1).optional(),
- // Absent everywhere except the API-key path; absent means "pinned".
+ // Stamped per request by the hosted transport, never baked into tokens;
+ // absent (self-host, SAM) means "pinned".
orgScope: z.enum(["pinned", "user"]).optional(),
baseUrl: z.string().url(),
// Compatibility fallback until workers-oauth-provider supplies the verified
@@ -98,8 +100,8 @@ export function createMcpToolContext(
const scopes = authInfo?.scopes ?? applicationAuth.scopes ?? [];
const orgScope = applicationAuth.orgScope ?? "pinned";
// Delegated/self-hosted modes have no member rows and a single implicit owner
- // per org; "pinned" without a role means owner. API keys ("user" scope) must
- // stamp the role from the user's active org membership in api-key-auth.ts.
+ // per org; "pinned" without a role means owner. Hosted ("user" scope)
+ // stamps the role from the member row per request in transport.ts.
const role =
applicationAuth.role ?? (orgScope === "pinned" ? "owner" : undefined);
if (!role) {
diff --git a/src/server/mcp/oauth-provider.ts b/src/server/mcp/oauth-provider.ts
index 9e976db3..b0e32546 100644
--- a/src/server/mcp/oauth-provider.ts
+++ b/src/server/mcp/oauth-provider.ts
@@ -333,6 +333,9 @@ async function handleOAuthConsentResponse(
);
}
+ // organizationId is only the fallback context for tools with no project
+ // argument; the hosted transport re-resolves it and stamps orgScope per
+ // request, so one authorization follows the user across every organization.
const props = createWorkersOAuthMcpProps({
userId: context.userId,
userEmail: context.userEmail,
diff --git a/src/server/mcp/project-auth.test.ts b/src/server/mcp/project-auth.test.ts
index 3a876edb..6ba42308 100644
--- a/src/server/mcp/project-auth.test.ts
+++ b/src/server/mcp/project-auth.test.ts
@@ -139,6 +139,7 @@ describe("withMcpProjectAuth with a user-scoped credential", () => {
it("rebinds auth and billing to the project's org and the member's role there", async () => {
const { withMcpProjectAuth } = await import("@/server/mcp/project-auth");
+ const userContext = makeToolContext({ orgScope: "user" });
const handler = vi.fn<
(
args: { projectId: string },
@@ -151,7 +152,7 @@ describe("withMcpProjectAuth with a user-scoped credential", () => {
await withMcpProjectAuth(handler)(
{ projectId: "project_123" },
- userScopedContext,
+ userContext,
);
expect(mocks.getMembership).toHaveBeenCalledWith("user_123", "org_other");
@@ -160,6 +161,9 @@ describe("withMcpProjectAuth with a user-scoped credential", () => {
expect(context.auth.organizationId).toBe("org_other");
expect(context.auth.role).toBe("admin");
expect(context.billing.organizationId).toBe("org_other");
+ // Written back so instrumentation credits the project's org.
+ expect(userContext.auth.organizationId).toBe("org_other");
+ expect(userContext.auth.role).toBe("admin");
});
it("rejects when the caller has no membership in the project's org", async () => {
diff --git a/src/server/mcp/project-auth.ts b/src/server/mcp/project-auth.ts
index 93344729..4416876f 100644
--- a/src/server/mcp/project-auth.ts
+++ b/src/server/mcp/project-auth.ts
@@ -13,10 +13,10 @@ async function requireProjectAccess(
) {
const { baseUrl, ...auth } = toolContext.auth;
- // User-scoped credentials (API keys) have no org binding: derive the org
- // from the project row, then authorize via the caller's membership in that
- // org. The returned auth is rebound to the project's org + the member's
- // role there, so billing and every downstream org read follow the project.
+ // User-scoped credentials have no org binding: derive the org from the
+ // project row, then authorize via the caller's membership in that org. The
+ // returned auth is rebound to the project's org + the member's role there,
+ // so billing and every downstream org read follow the project.
if (auth.orgScope === "user") {
const resolved = await ProjectService.getProjectWithOrganization(projectId);
const membership = resolved
@@ -33,6 +33,10 @@ async function requireProjectAccess(
organizationId: resolved.organizationId,
role: membership.role,
};
+ // instrumentMcpToolHandler wraps outside this gate and reads
+ // toolContext.auth after the handler returns, so the usage event and the
+ // activation milestone credit the project's org, not the fallback one.
+ toolContext.auth = { ...projectAuth, baseUrl };
return {
auth: projectAuth,
baseUrl,
diff --git a/src/server/mcp/tools/create-project.test.ts b/src/server/mcp/tools/create-project.test.ts
index 03eae7d8..e74d5009 100644
--- a/src/server/mcp/tools/create-project.test.ts
+++ b/src/server/mcp/tools/create-project.test.ts
@@ -151,14 +151,20 @@ describe("create_project with a user-scoped credential", () => {
});
it("creates in the named organization when the user is a member of it", async () => {
+ const userContext = makeToolContext({ orgScope: "user" });
await createProjectTool.handler(
{ name: "Acme", organizationId: "org_b" },
- userScopedContext,
+ userContext,
);
expect(mocks.createProject).toHaveBeenCalledWith("org_b", {
name: "Acme",
});
+ // Written back so instrumentation credits the target org.
+ expect(userContext.auth).toMatchObject({
+ organizationId: "org_b",
+ role: "admin",
+ });
});
it("rejects a organizationId the user is not a member of", async () => {
diff --git a/src/server/mcp/tools/create-project.ts b/src/server/mcp/tools/create-project.ts
index 1578163a..3af27b14 100644
--- a/src/server/mcp/tools/create-project.ts
+++ b/src/server/mcp/tools/create-project.ts
@@ -47,10 +47,11 @@ const inputSchema = {
type Args = z.infer<z.ZodObject<typeof inputSchema>>;
-// Which organization gets the project. Pinned credentials (OAuth tokens,
-// self-host, SAM) are bound to one org. User-scoped credentials (API keys)
-// span organizations, so an ambiguous target is an error listing the options —
-// the agent must confirm the choice with the user rather than guessing.
+// Which organization gets the project. Pinned credentials (self-host, SAM)
+// are bound to one org. User-scoped credentials (hosted OAuth tokens and API
+// keys) span organizations, so an ambiguous target is an error listing the
+// options — the agent must confirm the choice with the user rather than
+// guessing.
async function resolveTargetOrganization(
auth: Omit<ToolContext["auth"], "baseUrl">,
organizationId: string | undefined,
@@ -126,6 +127,9 @@ export const createProjectTool = {
handler: async (args: Args, context: ToolContext) => {
const { baseUrl, ...auth } = context.auth;
const target = await resolveTargetOrganization(auth, args.organizationId);
+ // Same as withMcpProjectAuth: instrumentation reads context.auth after
+ // the handler, so telemetry credits the target org.
+ context.auth = { ...context.auth, ...target };
// Same gate as the createProject server function — MCP and the dashboard
// must agree on who can create projects. The role is the caller's role
// in the TARGET organization, not the request-level one.
diff --git a/src/server/mcp/tools/list-projects.ts b/src/server/mcp/tools/list-projects.ts
index b5fa3d45..8be9ca4a 100644
--- a/src/server/mcp/tools/list-projects.ts
+++ b/src/server/mcp/tools/list-projects.ts
@@ -6,10 +6,10 @@ import { optionalMetaOutputSchema } from "@/server/mcp/output-schemas";
import { buildDashboardUrl } from "@/server/mcp/urls";
import { z } from "zod";
-// The org(s) whose projects the caller can see. Pinned credentials (OAuth
-// tokens, self-host) see the bound org; user-scoped credentials (API keys)
-// see every organization the user belongs to, labeled so the agent can tell
-// same-named projects apart.
+// The org(s) whose projects the caller can see. Pinned credentials (self-host,
+// SAM) see the bound org; user-scoped credentials (hosted OAuth tokens and API
+// keys) see every organization the user belongs to, labeled so the agent can
+// tell same-named projects apart.
async function listVisibleProjects(auth: Omit<ToolContext["auth"], "baseUrl">) {
if (auth.orgScope !== "user") {
const projects = await ProjectService.listProjects(auth.organizationId);
diff --git a/src/server/mcp/transport-v2.test.ts b/src/server/mcp/transport-v2.test.ts
index 1883a618..a4bcbbfa 100644
--- a/src/server/mcp/transport-v2.test.ts
+++ b/src/server/mcp/transport-v2.test.ts
@@ -17,6 +17,10 @@ vi.mock("@/server/auth/repositories/AuthRepository", () => ({
},
}));
+vi.mock("@/server/auth/default-hosted-organization", () => ({
+ resolveExistingActiveHostedOrganization: vi.fn(),
+}));
+
vi.mock("@/middleware/ensure-user/cloudflareAccess", () => ({
resolveCloudflareAccessContext: vi.fn(),
}));
diff --git a/src/server/mcp/transport.test.ts b/src/server/mcp/transport.test.ts
index da8ce4ef..2dcc6eac 100644
--- a/src/server/mcp/transport.test.ts
+++ b/src/server/mcp/transport.test.ts
@@ -21,10 +21,19 @@ const authRepositoryMocks = vi.hoisted(() => ({
getMembership: vi.fn(),
}));
+const hostedOrganizationMocks = vi.hoisted(() => ({
+ resolveExistingActiveHostedOrganization: vi.fn(),
+}));
+
vi.mock("@/server/auth/repositories/AuthRepository", () => ({
AuthRepository: authRepositoryMocks,
}));
+vi.mock("@/server/auth/default-hosted-organization", () => ({
+ resolveExistingActiveHostedOrganization:
+ hostedOrganizationMocks.resolveExistingActiveHostedOrganization,
+}));
+
vi.mock("@/middleware/ensure-user/cloudflareAccess", () => ({
resolveCloudflareAccessContext:
selfHostedAuthMocks.resolveCloudflareAccessContext,
@@ -235,12 +244,13 @@ describe("handleAuthenticatedOpenSeoMcpRequest", () => {
legacy: "reject",
}),
);
- // The transport stamps the per-request role into the props it hands the
- // server; roles are never baked into tokens.
+ // The transport stamps the per-request role and user scope into the props
+ // it hands the server; neither is baked into tokens.
expect(selfHostedAuthMocks.createOpenSeoMcpServer).toHaveBeenCalledWith({
[MCP_AUTH_CONTEXT_PROP]: {
...props[MCP_AUTH_CONTEXT_PROP],
role: "owner",
+ orgScope: "user",
},
});
});
@@ -309,6 +319,7 @@ describe("handleAuthenticatedOpenSeoMcpRequest", () => {
[MCP_AUTH_CONTEXT_PROP]: {
...props[MCP_AUTH_CONTEXT_PROP],
role: "owner",
+ orgScope: "user",
},
});
});
@@ -355,10 +366,44 @@ describe("handleAuthenticatedOpenSeoMcpRequest", () => {
expect(response.status).toBe(403);
});
- it("rejects a token whose user is no longer a member of the granted org", async () => {
- // Tokens pin organizationId at consent time; once the membership is gone
- // the token must stop working and push the client back through OAuth.
+ it("rebinds a token to the user's active org when the consent-time membership is gone", async () => {
authRepositoryMocks.getMembership.mockResolvedValue(null);
+ hostedOrganizationMocks.resolveExistingActiveHostedOrganization.mockResolvedValue(
+ { organizationId: "org-2", role: "member" },
+ );
+ // No orgScope: a grant minted before the flag existed heals the same way.
+ const props = createWorkersOAuthMcpProps({
+ userId: "user-1",
+ userEmail: "[email protected]",
+ organizationId: "org-1",
+ baseUrl: "https://open-seo.test",
+ clientId: "client-1",
+ scopes: ["mcp"],
+ });
+
+ const response = await handleAuthenticatedOpenSeoMcpRequest(
+ createMcpRequest(),
+ props,
+ {},
+ { ...ctx, props },
+ );
+
+ expect(response.status).toBe(200);
+ expect(selfHostedAuthMocks.createOpenSeoMcpServer).toHaveBeenCalledWith({
+ [MCP_AUTH_CONTEXT_PROP]: {
+ ...props[MCP_AUTH_CONTEXT_PROP],
+ organizationId: "org-2",
+ role: "member",
+ orgScope: "user",
+ },
+ });
+ });
+
+ it("rejects a token whose user belongs to no organization", async () => {
+ authRepositoryMocks.getMembership.mockResolvedValue(null);
+ hostedOrganizationMocks.resolveExistingActiveHostedOrganization.mockResolvedValue(
+ null,
+ );
const props = createWorkersOAuthMcpProps({
userId: "user-1",
userEmail: "[email protected]",
diff --git a/src/server/mcp/transport.ts b/src/server/mcp/transport.ts
index b9b7d4f4..cc8ebbd6 100644
--- a/src/server/mcp/transport.ts
+++ b/src/server/mcp/transport.ts
@@ -21,6 +21,7 @@ import {
import { getPublicOrigin } from "@/server/mcp/public-origin";
import { createOpenSeoMcpServer } from "@/server/mcp/server";
import { AuthRepository } from "@/server/auth/repositories/AuthRepository";
+import { resolveExistingActiveHostedOrganization } from "@/server/auth/default-hosted-organization";
// Mirrors the agents SDK's DEFAULT_CORS_OPTIONS so legacy responses carry the
// same CORS surface as the modern handler's.
@@ -153,6 +154,19 @@ function createRequestHandler(
};
}
+// Hosted credentials (OAuth grants and API keys) are user-scoped: the
+// organizationId they carry is only the fallback context for tools with no
+// project argument, so keep it while the membership holds, else rebind to the
+// user's current active org. Null only when they belong to no org at all.
+async function resolveRequestOrganization(
+ userId: string,
+ organizationId: string,
+) {
+ const membership = await AuthRepository.getMembership(userId, organizationId);
+ if (membership) return { organizationId, role: membership.role };
+ return resolveExistingActiveHostedOrganization(userId);
+}
+
export async function handleAuthenticatedOpenSeoMcpRequest(
request: Request,
props: unknown,
@@ -179,14 +193,14 @@ export async function handleAuthenticatedOpenSeoMcpRequest(
// Tokens snapshot organizationId at consent and refresh copies it verbatim,
// so the grant can outlive the membership (member removed, org changed).
- // Re-check the member row per request; 401 invalid_token pushes compliant
- // clients back through OAuth, where consent stamps their current org.
+ // Re-resolve per request; 401 invalid_token only once the user belongs to
+ // no organization, pushing compliant clients back through OAuth.
const authContext = result.data[MCP_AUTH_CONTEXT_PROP];
- const membership = await AuthRepository.getMembership(
+ const organization = await resolveRequestOrganization(
authContext.userId,
authContext.organizationId,
);
- if (!membership) {
+ if (!organization) {
return new Response("Organization access revoked", {
status: 401,
headers: { "WWW-Authenticate": 'Bearer error="invalid_token"' },
@@ -197,10 +211,15 @@ export async function handleAuthenticatedOpenSeoMcpRequest(
// own; passing authContext explicitly hands it the schema-validated copy
// (with the per-request role stamped in — roles are never baked into
// tokens) and keeps this path symmetrical with self-hosted, which has no
- // ctx.props.
+ // ctx.props. orgScope is stamped here rather than read from the token so
+ // grants minted before it existed are user-scoped too: project-scoped tools
+ // authorize per call via membership in the project's org, so one
+ // authorization follows the user across every organization they belong to.
const requestProps = createWorkersOAuthMcpProps({
...authContext,
- role: membership.role,
+ organizationId: organization.organizationId,
+ role: organization.role,
+ orgScope: "user",
});
return createRequestHandler(requestProps, [
hostedUrl.hostname,