# MCP servers

> Protect an MCP server with tokens bound to it, connect Claude Code, or verify the JWTs your own sign-in issues.

From `docs/guide.md`, `examples/mcpserver/README.md`, `README.md` in tensile-tools/tensile-auth at commit `e66760d` (v0.4.1-7-ge66760d). The HTML page is https://auth.tensile.tools/docs/guides/mcp.

`oauth.Config.Resources` registers an MCP server as a resource (RFC 8707), and the provider binds every token for it to that resource. `mcpauth` protects the MCP route and accepts only tokens for its resource.

To serve the MCP server in the same process as your app, route its path beside the `authhttp.Mux`, on a parent `http.ServeMux`:

```go
root := http.NewServeMux()
protector.Register(root, "/mcp", mcpServer, nil) // protector from mcpauth.New
root.Handle("/", mux)                            // your authhttp.Mux
```

Don't register `/mcp` behind the Mux. The Mux authenticates every request and refuses a token bound to a resource with 401 unless `authhttp.WithResource` lists that resource. The refusal's detail says the token is for a different resource, and the log names the resource. Add `authhttp.WithResource(uri)` only when your app's own routes should accept the MCP server's tokens too.

MCP clients get tokens with the authorization code flow and PKCE. The device flow doesn't issue tokens for a resource: a device authorization request with `resource` gets `invalid_target`. See `examples/mcpserver`.

## A TypeScript MCP server

`mcpauth` is a Go package. An MCP server in a Node, Bun, or Deno app that runs on `tensile-auth-server` does its three jobs itself, with `@tensile-tools/auth`:

- **Serve the Protected Resource Metadata** (RFC 9728) at `/.well-known/oauth-protected-resource` followed by the MCP path, for example `/.well-known/oauth-protected-resource/mcp`. The server doesn't serve this document: through the proxy, that path answers 404.
- **Answer 401 with a challenge** that names the metadata: `WWW-Authenticate: Bearer resource_metadata="…"`. MCP clients start their sign-in from it. The server's own 401 carries no `resource_metadata`.
- **Check each request with the token's audience.** Call the core client's `check` with `resource` set to the MCP server's canonical URI. Without `resource`, `/v1/check` refuses every token bound to a resource with 401. The adapters' `need` and `authenticate` take no `resource`, so call `check` directly.

`/v1/check` with `resource` refuses a token bound to another resource, but it still accepts a credential bound to none, such as a session cookie, a personal access token, or an agent's token. Its principal doesn't say which resource a token is for, so the route also refuses any principal whose `kind` isn't `oauth`.

Configure the server with the resource, and give sessions the scopes that tokens for it need, because a token gets only scopes the approving session holds. Resources come only from the TOML file; with the image, mount it at `/etc/tensile-auth/config.toml`:

```toml
[oauth]
enabled = true

[[oauth.resources]]
uri = "http://localhost:3000/mcp"
name = "Notes"
scopes = ["notes:read"]

[sessions]
default_scopes = ["notes:read"]
```

For local development, the resource may use `http://` on a loopback host, such as `http://localhost:3000/mcp`. Server 0.4.1 refuses an `http://` resource at startup; later releases accept it on a loopback host. Every other resource uses `https://`. The MCP server's origin must also be in `origins`, because `/v1/check` refuses a request URL on any other origin.

The issuer defaults to the first origin, so the app's proxy forwards `/login/oauth/` and `/.well-known/` to the server, and the app serves the consent page; see [OAuth](/docs/guides/oauth). A Hono app looks like this:

```ts
import { Hono } from 'hono'
import { credentialOf, problemResponse, requestInfo, TensileError, unavailable } from '@tensile-tools/auth'
import { tensile, type TensileEnv } from '@tensile-tools/auth/hono'
import { serveMcp } from './mcp-server.ts' // your MCP server's Streamable HTTP transport

const origin = 'http://localhost:3000'  // the first origin in the server's origins
const resource = `${origin}/mcp`        // the uri in [[oauth.resources]]
const metadata = `${origin}/.well-known/oauth-protected-resource/mcp`
const scopes = ['notes:read']

const auth = tensile({ url: process.env.TENSILE_AUTH_URL!, appKey: process.env.TENSILE_AUTH_APP_KEY! })
const app = new Hono<TensileEnv>()

// The metadata route comes before the /.well-known/ proxy, which would answer it with 404.
app.get('/.well-known/oauth-protected-resource/mcp', c => c.json({
  resource, authorization_servers: [origin], scopes_supported: scopes, bearer_methods_supported: ['header'],
}))
app.all('/.well-known/*', auth.proxy({ wellKnown: true }))
app.all('/login/oauth/*', auth.proxy({ oauth: true }))
app.all('/auth/*', auth.proxy())

function challenge(status: 401 | 403, error?: string): Response {
  const params = [`resource_metadata="${metadata}"`, `scope="${scopes.join(' ')}"`]
  if (error) params.push(`error="${error}"`)
  return new Response(null, { status, headers: { 'www-authenticate': `Bearer ${params.join(', ')}`, 'cache-control': 'no-store' } })
}

app.all('/mcp', async c => {
  if (!c.req.header('authorization')) return challenge(401)
  let r
  try {
    r = await auth.client.check({
      credential: credentialOf(c.req.raw)!,
      request: requestInfo(c.req.raw),
      need: { action: 'mcp.call', scopes },
      resource,
    })
  } catch (err) {
    if (err instanceof TensileError) return problemResponse(unavailable) // 503, never 401
    throw err
  }
  if (!r.allowed) return r.problem.code === 'scope_missing' ? challenge(403, 'insufficient_scope') : challenge(401, 'invalid_token')
  if (r.principal.kind !== 'oauth') return challenge(401, 'invalid_token')
  return serveMcp(c.req.raw, r.principal) // r.principal.user is the person the client acts for
})

export default app
```

Revoking the client's grant stops its next request, because each request runs `check`; see [OAuth grants](/docs/guides/sessions#oauth-grants).

## Connect Claude Code to the example

1. Start the server:

   ```sh
   go run ./examples/mcpserver
   ```

   It listens on `localhost:8080` and uses `http://localhost:8080` as its issuer. The provider accepts `http` only for `localhost`.

2. Add the server to Claude Code:

   ```sh
   claude mcp add --transport http notes http://localhost:8080/mcp
   ```

3. In Claude Code, run `/mcp`, choose `notes`, and choose to authenticate. Claude Code reads the Protected Resource Metadata from the `401` challenge, finds the authorization server, and identifies itself with its client ID metadata document, `https://claude.ai/oauth/claude-code-client-metadata`. The default CIMD allowlist admits `claude.ai`, so the server fetches that document and needs no registration.

4. Your browser opens the sign-in page. Sign in with any name.

5. The consent page shows:

   - the client's name, Claude Code, which is its own claim, and its verified host, `claude.ai`;
   - the host the approval goes to, `localhost`, with a warning, because any program on your computer can listen on a loopback address;
   - the resource, Notes at `http://localhost:8080/mcp`;
   - the scopes, `notes:read` and `notes:write`.

   Choose **Allow**. Every approval is recorded before the code is issued, and a loopback redirect never skips this page.

6. Ask Claude Code to add a note and list your notes. It calls `notes_add` and `notes_list` with a token whose audience is `http://localhost:8080/mcp`. That token works nowhere else: not at another MCP server, and not at the provider's userinfo endpoint.

7. Open `http://localhost:8080/audit`. Each tool call is a `tool_called` event with the tool, the decision, and a hash of the arguments, never the arguments themselves.

8. Open `http://localhost:8080/connections` and choose **Revoke**. The next tool call from Claude Code gets `401` with `error="invalid_token"`, at once, because the token is a session that the server checks on every request.

## Protect an MCP server with the sign-in you already have

You don't need the library's provider to use `mcpauth`. If your authorization server, such as Auth0, Okta, Keycloak, or Clerk, issues JWT access tokens, verify them with `mcpauth.JWT`:

```go
v, err := mcpauth.JWT(mcpauth.JWTConfig{
	Issuer:   "https://example.us.auth0.com/", // exactly as the tokens' iss holds it
	Audience: "https://notes.example.com/mcp", // configure your server to put this in aud
})
p, err := mcpauth.New(mcpauth.Options{
	Resource:             "https://notes.example.com/mcp",
	AuthorizationServers: []string{"https://example.us.auth0.com/"},
	Verifier:             v,
	Scopes:               []string{"notes:read"},
	ToolScopes:           map[string][]string{"notes_list": nil, "notes_add": {"notes:write"}},
})
p.Register(mux, "/mcp", server, &mcp.StreamableHTTPOptions{Stateless: true})
```

The verifier finds the keys through the issuer's metadata, accepts only asymmetric signatures, and requires the issuer, an expiry, and your MCP server as audience. A JWT can't be revoked before it expires, so keep tokens short or set `MaxAge`.

If your application has its own login but no OAuth server, `authhttp.Bridge` puts that login in front of the library's provider and consent page. See [`examples/mcpserver`](/docs/guides/mcp) with `-own-login`, and the design.

An MCP server in a Node, Bun, or Deno app on `tensile-auth-server` doesn't use `mcpauth`: it serves its metadata and its 401 challenge itself, and checks each request with the SDK's `check` and `resource`. See [A TypeScript MCP server](/docs/guides/mcp#a-typescript-mcp-server).
