> ## Documentation Index
> Fetch the complete documentation index at: https://docs.skybridge.tech/llms.txt
> Use this file to discover all available pages before exploring further.

# Authenticate Users

> Know who's behind every tool call

![Authenticate Users](https://docs.skybridge.tech/images/auth.webp)

[Tool](https://docs.skybridge.tech/build/tools.md) calls are anonymous by default: nothing in the protocol tells you who's asking. [OAuth](https://oauth.net/2/) closes that gap, and the host does most of the work: it discovers your authorization server, signs the user in, refreshes tokens, and attaches a Bearer token to every request. Your server keeps three jobs: publish the discovery metadata, verify the tokens, and read the user in your handlers.

> [!TIP]
>
> Using [Auth0](https://docs.skybridge.tech/guides/auth-providers.md#auth0), [Clerk](https://docs.skybridge.tech/guides/auth-providers.md#clerk), [Descope](https://docs.skybridge.tech/guides/auth-providers.md#descope), [Stytch](https://docs.skybridge.tech/guides/auth-providers.md#stytch), [WorkOS](https://docs.skybridge.tech/guides/auth-providers.md#workos), or [any other OAuth provider](https://docs.skybridge.tech/guides/auth-providers.md#any-other-provider)? Connect it in one line instead of wiring this by hand, and still [mix public and authenticated tools](#mix-public-and-authenticated-tools) with `auth: { allowsAnonymous: true }`.

Here's a complete server where every tool requires sign-in:

```ts server.ts theme={null}
import { Skybridge, mcpAuthMetadataRouter, requireBearerAuth } from "skybridge/server";
import { z } from "zod";

import { verifyAccessToken } from "./auth.js";

export const app = new Skybridge({
  name: "personal-shopper",
  version: "0.0.1",
  handler: (server) =>
    server
      .registerTool(
        {
          name: "search-products",
          description: "Show products matching a query in a carousel.",
          inputSchema: { query: z.string() },
          securitySchemes: [{ type: "oauth2" }],
          view: { component: "carousel" },
        },
        async ({ query }, extra) => ({
          structuredContent: { products: await search(query, extra.http?.authInfo) },
        }),
      )
      .registerTool(
        {
          name: "create-checkout",
          description: "Create a checkout session for the given products.",
          inputSchema: { productIds: z.array(z.string()) },
          securitySchemes: [{ type: "oauth2", scopes: ["checkout"] }],
        },
        async ({ productIds }, extra) => ({
          structuredContent: { url: await checkout(productIds, extra.http?.authInfo) },
        }),
      ),
})
  .use(
    mcpAuthMetadataRouter({
      oauthMetadata: {
        issuer: "https://auth.myshop.com",
        authorization_endpoint: "https://auth.myshop.com/authorize",
        token_endpoint: "https://auth.myshop.com/token",
        response_types_supported: ["code"],
      },
      resourceServerUrl: new URL(process.env.SERVER_URL),
    }),
  )
  .use("/mcp", requireBearerAuth({ verifier: { verifyAccessToken } }));
```

The sections below cover publishing the discovery metadata, verifying tokens with a middleware, declaring auth per tool, reading the user in handlers, and mixing public and authenticated tools.

## Publish Discovery Metadata

Hosts find your authorization server through standard metadata documents ([RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728)). [`mcpAuthMetadataRouter`](https://docs.skybridge.tech/api-reference/mcp-auth-metadata-router) serves them at `/.well-known/oauth-protected-resource`, so the host can perform the authentication flow.

```ts server.ts highlight={2-12} theme={null}
export const app = new Skybridge({ name: "personal-shopper", version: "0.0.1", handler })
  .use(
    mcpAuthMetadataRouter({
      oauthMetadata: {
        issuer: "https://auth.myshop.com",
        authorization_endpoint: "https://auth.myshop.com/authorize",
        token_endpoint: "https://auth.myshop.com/token",
        response_types_supported: ["code"],
      },
      resourceServerUrl: new URL(process.env.SERVER_URL),
    }),
  )
  .use("/mcp", requireBearerAuth({ verifier: { verifyAccessToken } }));
```

The endpoint values come from your OAuth provider's documentation. `resourceServerUrl` is this server's public URL: localhost in development, the [tunnel](https://docs.skybridge.tech/test/tunnel.md) URL when testing in a host, your domain in production.

## Verify Tokens with a Middleware

Once the user is signed in, every request carries `Authorization: Bearer <token>`. [`requireBearerAuth`](https://docs.skybridge.tech/api-reference/require-bearer-auth) validates it before any handler runs: missing, invalid, or expired tokens get a 401, insufficient scopes a 403.

It takes a [verifier](https://docs.skybridge.tech/api-reference/verifier.md) you write, with one method: `verifyAccessToken(token)` resolves with an [`AuthInfo`](https://docs.skybridge.tech/api-reference/verifier#authinfo) (handlers receive it as `extra.http?.authInfo`) or throws `OAuthError` (the middleware answers 401).

```ts server.ts highlight={13} theme={null}
export const app = new Skybridge({ name: "personal-shopper", version: "0.0.1", handler })
  .use(
    mcpAuthMetadataRouter({
      oauthMetadata: {
        issuer: "https://auth.myshop.com",
        authorization_endpoint: "https://auth.myshop.com/authorize",
        token_endpoint: "https://auth.myshop.com/token",
        response_types_supported: ["code"],
      },
      resourceServerUrl: new URL(process.env.SERVER_URL),
    }),
  )
  .use("/mcp", requireBearerAuth({ verifier: { verifyAccessToken } }));
```

```ts auth.ts theme={null}
import { type AuthInfo, OAuthError } from "skybridge/server";

export async function verifyAccessToken(token: string): Promise<AuthInfo> {
  try {
    // Provider-specific: JWKS verification, introspection endpoint, or SDK
    const payload = await validateToken(token);

    return {
      token,
      clientId: payload.clientId,
      scopes: payload.scopes,
      expiresAt: payload.expiresAt,
      extra: { subject: payload.sub },
    };
  } catch (err) {
    throw new OAuthError(
      "invalid_token",
      err instanceof Error ? err.message : "Token validation failed",
    );
  }
}
```

The validation body is provider-specific: [JWKS](https://datatracker.ietf.org/doc/html/rfc7517) verification for [JWT](https://datatracker.ietf.org/doc/html/rfc7519)-issuing providers, an introspection call for opaque tokens, or the provider's own middleware in place of [`requireBearerAuth`](https://docs.skybridge.tech/api-reference/require-bearer-auth).

## Type the Claims You Read

The claim shape belongs to the verifier, so handlers get it without declaring anything. On the [provider path](https://docs.skybridge.tech/guides/auth-providers.md) each provider ships the claims its own docs promise, and a type argument adds the ones your tenant sends:

```ts server.ts theme={null}
oauth: workosProvider<{ tenant: string }>({ domain, audience }),
```

Writing the verifier yourself? Type it `TokenVerifier<Claims>` and the shape flows the same way.

None of this is checked at runtime, so keep anything the IdP may omit optional. No provider ships `email` in an access token by default: WorkOS, Clerk, Descope and Stytch can add one through a JWT template or claims action, and Auth0 needs a namespaced claim, since it drops non-namespaced ones.

## Mix Public and Authenticated Tools

Serving both anonymous and signed-in callers from one server takes three changes to the fully authenticated setup.

> [!TIP]
>
> On the [provider path](https://docs.skybridge.tech/guides/auth-providers.md) (the `oauth` config field), these three steps collapse into one `auth` declaration per tool, and Skybridge enforces it for you:
>
> ```ts theme={null}
> server
>   .registerTool({ name: "search-products", auth: { allowsAnonymous: true }, /* … */ }, handler)
>   .registerTool({ name: "create-checkout", auth: { scopes: ["checkout"] }, /* … */ }, handler);
> ```
>
> Any `auth: { allowsAnonymous: true }` tool makes the server serve anonymous callers; every other tool stays sign-in-gated, with scopes enforced before the handler. No manual middleware swap or handler guard. The lower-level steps below apply when you wire the middleware by hand instead.

### Switch the Middleware

[`optionalBearerAuth`](https://docs.skybridge.tech/api-reference/optional-bearer-auth) validates the token when present, lets the request through when absent, and still rejects invalid tokens with a 401. Unauthenticated requests now reach your handlers.

```ts server.ts highlight={2} theme={null}
export const app = new Skybridge({ name: "personal-shopper", version: "0.0.1", handler })
  .use("/mcp", optionalBearerAuth({ verifier: { verifyAccessToken } }));
```

### Declare Tool Visibility

Three declarations cover the combinations:

| [`securitySchemes`](https://docs.skybridge.tech/api-reference/register-tool#securityschemes) | Meaning |
| - | - |
| `[{ type: "oauth2" }]` | Requires sign-in |
| `[{ type: "noauth" }]` | Works signed out |
| `[{ type: "noauth" }, { type: "oauth2" }]` | Works signed out, does more when signed in |

```ts server.ts highlight={5} theme={null}
server.registerTool(
  {
    name: "search-products",
    // …
    securitySchemes: [{ type: "noauth" }, { type: "oauth2" }],
  },
  async ({ query }, extra) => ({
    structuredContent: { products: await search(query, extra.http?.authInfo) },
  }),
);
```

`search-products` lists both schemes: anonymous callers browse the public catalog, signed-in callers get results scoped to their account. `extra.http?.authInfo` is set or `undefined` accordingly.

### Guard the Handler

With unauthenticated requests reaching [handlers](https://docs.skybridge.tech/api-reference/register-tool.md#handler), the scope check is no longer a formality: it's the only gate on protected tools.

```ts server.ts highlight={8-10} theme={null}
server.registerTool(
  {
    name: "create-checkout",
    // …
    securitySchemes: [{ type: "oauth2", scopes: ["checkout"] }],
  },
  async ({ productIds }, extra) => {
    if (!extra.http?.authInfo?.scopes.includes("checkout")) {
      return { content: "Sign in to check out.", isError: true };
    }
    return {
      structuredContent: { url: await checkout(productIds, extra.http?.authInfo) },
    };
  },
);
```

> [card] [All done!](https://docs.skybridge.tech/test)
>
> You now know how to authenticate users. Learn how to test your MCP App in the next chapter.

## Go Further

> [card] [Register Tools](https://docs.skybridge.tech/build/tools.md)
>
> Define what humans and agents can do

> [card] [Create Views](https://docs.skybridge.tech/build/view.md)
>
> Craft interactive UIs rendered in conversation

> [card] [Manage State](https://docs.skybridge.tech/build/state.md)
>
> Decide what the model sees


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.