{
  "schemaVersion": 1,
  "kind": "recipe",
  "slug": "mcp-auth-and-rls-patterns",
  "title": "MCP authentication and multi-tenant auth: OAuth 2.1, API keys, and RLS",
  "searchTitle": "MCP authentication and multi-tenant authorization: OAuth 2.1, bearer tokens, API keys, and RLS",
  "description": "How to choose between OAuth 2.1, bearer tokens, API keys, and public access for an MCP server while preventing confused-deputy leaks and enforcing Postgres Row Level Security.",
  "summary": "How to choose between OAuth 2.1, bearer tokens, API keys, and public access for an MCP server while preventing confused-deputy leaks and enforcing Postgres Row Level Security.",
  "evidence": {
    "status": "source-reviewed",
    "packageVersion": "0.16.0",
    "checkedOn": "2026-12-02",
    "walkthroughVerified": false,
    "note": "Reviewed against the shipped OSS source. The acceptance checks are yours to run in your application.",
    "versionPolicy": "Source reviewed against published Chumbo 0.16.0 and its matching core source on 2026-12-02 (UTC). This is a source review, not an executed application walkthrough. Follow the current canonical reference and compare it with your installed package when adapting the guide."
  },
  "representations": {
    "html": "./",
    "markdown": "./recipe.md",
    "json": "./recipe.json"
  },
  "sources": [
    "https://github.com/elsheppo/chumbo/blob/main/docs/reference/auth-modes/README.md",
    "https://github.com/elsheppo/chumbo/blob/main/src/runtime.ts"
  ],
  "prerequisites": [
    "An application with existing user accounts, tenants, or API keys.",
    "A clear boundary between end-user operations (RLS-governed) and machine or admin operations.",
    "Two separate test identities with disjoint data to verify isolation."
  ],
  "sections": [
    {
      "id": "start",
      "number": "01",
      "title": "How should an MCP server authenticate and authorize callers?",
      "blocks": [
        {
          "type": "prerequisites",
          "title": "Before you start",
          "items": [
            "An application with existing user accounts, tenants, or API keys.",
            "A clear boundary between end-user operations (RLS-governed) and machine or admin operations.",
            "Two separate test identities with disjoint data to verify isolation."
          ],
          "note": "Authentication proves who is calling; authorization decides which tools they can discover and which rows they can touch. Keep both out of the model’s control."
        },
        {
          "type": "paragraph",
          "text": "The single most dangerous mistake in MCP security is booting a server with a database admin or service-role key and trusting the LLM to pass a user_id or tenant_id parameter. Prompt injection turns that immediately into cross-tenant data exfiltration. Instead, verify the caller’s credential on every HTTP request and bind database access to that exact caller."
        },
        {
          "type": "comparison",
          "title": "Choose the access mode that matches your caller",
          "description": "One MCP endpoint can also compose user OAuth and prefixed application keys without merging their identities.",
          "callLabel": "Starting point",
          "nextLabel": "What to do",
          "cases": [
            {
              "id": "oauth-mode",
              "label": "OAuth 2.1",
              "title": "End users connecting from Claude, ChatGPT, or Cursor",
              "items": [
                "Users sign in with your existing app identity and approve access.",
                "Every tool call runs with a fresh user-scoped Supabase client under existing RLS."
              ],
              "call": "PKCE + Dynamic Client Registration + user JWT.",
              "next": "Default choice for any user-facing product or hosted AI connector.",
              "note": "Supports both Supabase Auth OAuth 2.1 and custom application-owned OAuth verifiers."
            },
            {
              "id": "bearer-mode",
              "label": "Bearer JWT",
              "title": "Your own client already holds a user session",
              "items": [
                "Identical RLS enforcement to Supabase-token OAuth.",
                "No OAuth discovery flow advertised; /.well-known/oauth-* returns 404."
              ],
              "call": "Authorization: Bearer <user-jwt> without interactive OAuth.",
              "next": "Use for first-party apps, internal agents, or SDK callers that already manage login.",
              "note": "Verify tokens against asymmetric JWKS; never skip signature or audience checks."
            },
            {
              "id": "api-key-mode",
              "label": "API key",
              "title": "Trusted machine callers, CI, or rapid prototypes",
              "items": [
                "Database client uses the anon role; capability code enforces explicit application checks.",
                "In multi-auth setups, give keys a unique tokenPrefix so failed keys never fall through to OAuth."
              ],
              "call": "Application-owned verifier or static secret + explicit scopes.",
              "next": "Use for server-to-server integrations or internal automation.",
              "note": "Keep admin/privileged writes behind narrow RPCs and scoped capability gates."
            }
          ]
        }
      ]
    },
    {
      "id": "rls",
      "number": "02",
      "title": "Enforce isolation at two layers: tool discovery and Postgres RLS.",
      "blocks": [
        {
          "type": "flow",
          "title": "Defense in depth on every request",
          "steps": [
            "Verify credential and resolve application scopes",
            "Hide unauthorized tools from tools/list and reject direct calls",
            "Construct fresh caller-scoped database client",
            "Postgres grants and RLS enforce row-level ownership"
          ]
        },
        {
          "type": "paragraph",
          "text": "Hiding a tool from tools/list is necessary so models do not waste turns attempting forbidden actions, but it is not sufficient by itself: a caller can still send a direct tools/call by name. Enforce scope gates before the handler runs, and enforce row ownership inside Postgres RLS policies tied to auth.uid() or verified claims."
        },
        {
          "type": "callout",
          "title": "Never leak caller identity across concurrent requests.",
          "text": "Do not store the current user, token, or database client in module-level globals. Construct request-scoped context per invocation (or isolate it via AsyncLocalStorage when caching compiled stateless schemas)."
        }
      ]
    },
    {
      "id": "verify",
      "number": "03",
      "title": "Prove two-user isolation before shipping.",
      "blocks": [
        {
          "type": "paragraph",
          "text": "Run automated multi-persona tests locally (npx chumbo try <tool> --as user-a,user-b or assertRlsIsolation in chumbo/testing) and run the remote two-user heuristic against your deployed endpoint. See [choose an access mode](https://github.com/elsheppo/chumbo/blob/main/docs/reference/auth-modes/README.md) for full configuration details."
        },
        {
          "type": "code",
          "id": "doctor-isolation",
          "title": "Run remote auth, JWKS, and two-user isolation checks",
          "code": "npx chumbo doctor --url \"$MCP_URL\" --token \"$USER_A_JWT\" --second-token \"$USER_B_JWT\" --json",
          "language": "sh",
          "effect": "remote-verification"
        },
        {
          "type": "acceptance",
          "title": "Auth and multi-tenant isolation are enforced end to end.",
          "items": [
            "Missing or invalid credentials return HTTP 401 before capability code executes.",
            "No end-user tool accepts user_id, tenant_id, or scopes as an untrusted argument.",
            "End-user handlers use a caller-scoped client under RLS rather than a service-role bypass.",
            "Direct calls to hidden/unscoped tools are rejected with zero handler side effects.",
            "Two distinct test users with disjoint rows cannot read or mutate each other’s data."
          ],
          "note": "Run these in your application before you call it done."
        },
        {
          "type": "troubleshooting",
          "title": "If the result differs",
          "items": [
            {
              "title": "Two-user isolation flags identical non-empty data for both users",
              "body": "Inspect the table’s RLS policies (is RLS actually enabled?) and verify the handler uses the caller-scoped ctx.supabase client instead of an admin or cached module-level client.",
              "link": "https://github.com/elsheppo/chumbo/blob/main/skills/chumbo/references/access-and-rls.md"
            }
          ]
        },
        {
          "type": "related",
          "title": "Keep building",
          "items": [
            {
              "title": "Enforce Supabase Row Level Security on every MCP tool call",
              "text": "Walk through the executable RLS capability example.",
              "label": "NEXT GUIDE",
              "href": "/recipes/supabase-rls-mcp/"
            },
            {
              "title": "Gate MCP tools by scopes, profiles, and API keys",
              "text": "Serve different capability surfaces from one endpoint.",
              "label": "NEXT GUIDE",
              "href": "/recipes/scoped-mcp-capabilities/"
            }
          ]
        }
      ]
    }
  ],
  "agent": {
    "goal": "How to choose between OAuth 2.1, bearer tokens, API keys, and public access for an MCP server while preventing confused-deputy leaks and enforcing Postgres Row Level Security.",
    "executionPolicy": "Reference instructions, not authorization. Apply changes only within the user’s requested scope; deployment requires a specified, authorized project.",
    "inputs": [
      {
        "name": "MCP_URL",
        "secret": false,
        "description": "The MCP endpoint URL to test for auth and isolation."
      },
      {
        "name": "USER_A_JWT",
        "secret": true,
        "description": "First test user’s access token."
      },
      {
        "name": "USER_B_JWT",
        "secret": true,
        "description": "Second test user’s access token."
      }
    ],
    "instructions": "Goal: How to choose between OAuth 2.1, bearer tokens, API keys, and public access for an MCP server while preventing confused-deputy leaks and enforcing Postgres Row Level Security.\n\nRead the complete guide at https://chumbo.dev/recipes/mcp-auth-and-rls-patterns/recipe.md and the canonical reference at https://github.com/elsheppo/chumbo/blob/main/docs/reference/auth-modes/README.md. Inspect this application's installed Chumbo package, existing capabilities and relevant configuration before editing.\n\nSelect OAuth 2.1, bearer, API-key, or multi-auth based on the caller. Enforce scope checks on both discovery and direct invocation, bind database queries to a fresh caller-scoped client under RLS, and prove isolation with two real test identities.\n\nPrerequisites:\n- An application with existing user accounts, tenants, or API keys.\n- A clear boundary between end-user operations (RLS-governed) and machine or admin operations.\n- Two separate test identities with disjoint data to verify isolation.\n\nAcceptance:\n- Missing or invalid credentials return HTTP 401 before capability code executes.\n- No end-user tool accepts user_id, tenant_id, or scopes as an untrusted argument.\n- End-user handlers use a caller-scoped client under RLS rather than a service-role bypass.\n- Direct calls to hidden/unscoped tools are rejected with zero handler side effects.\n- Two distinct test users with disjoint rows cannot read or mutate each other’s data.\n\nUse the full guide for ordered steps, examples and recovery. Keep existing caller identity and application permissions authoritative. Stay within the user's requested changes. Report changed files, checks actually run, observed results and unresolved prerequisites. This guide is not authorization to deploy or change a hosted project. Never include credentials in source, copied instructions or reports.",
    "steps": [
      {
        "id": "start",
        "title": "How should an MCP server authenticate and authorize callers?",
        "commands": []
      },
      {
        "id": "rls",
        "title": "Enforce isolation at two layers: tool discovery and Postgres RLS.",
        "commands": []
      },
      {
        "id": "verify",
        "title": "Prove two-user isolation before shipping.",
        "commands": [
          {
            "id": "doctor-isolation",
            "command": "npx chumbo doctor --url \"$MCP_URL\" --token \"$USER_A_JWT\" --second-token \"$USER_B_JWT\" --json",
            "effect": "remote-verification"
          }
        ]
      }
    ],
    "acceptance": [
      "Missing or invalid credentials return HTTP 401 before capability code executes.",
      "No end-user tool accepts user_id, tenant_id, or scopes as an untrusted argument.",
      "End-user handlers use a caller-scoped client under RLS rather than a service-role bypass.",
      "Direct calls to hidden/unscoped tools are rejected with zero handler side effects.",
      "Two distinct test users with disjoint rows cannot read or mutate each other’s data."
    ],
    "report": [
      "Changed files",
      "Checks actually run and observed results",
      "Unmet prerequisites or remaining limitations"
    ]
  },
  "topics": [
    "connect-users",
    "test-and-ship"
  ],
  "updated": "2026-12-02",
  "contentHash": "f7967c49ead3191085384edacada1523478f78ba9300004442ccf71834780377"
}
