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

# Anthropic SDK

> Use Civic with Anthropic's Messages API using the native MCP connector

## Overview

Integrate Civic with Anthropic's Messages API using the **native MCP connector** — built directly into the API, no separate MCP client needed.

<Note>
  **Native MCP Support**: Add a `mcp_servers` parameter to your `messages.create()` call. Claude discovers and calls tools automatically — no tool looping required.
</Note>

## Prerequisites

* Civic account at [app.civic.com](https://app.civic.com) with at least one MCP server connected
* Anthropic API key from [console.anthropic.com](https://console.anthropic.com)

## Installation

```bash theme={null}
npm install @anthropic-ai/sdk
```

No MCP SDK required — the connector is built into the Anthropic SDK.

## Authentication

Choose the path that matches your use case:

<Tabs>
  <Tab title="Backend / Script (Civic Token)">
    For autonomous agents, scripts, and server-side code that runs without a user browser session — use a Civic token directly.

    ### Generate a Civic Token

    1. Log in to [app.civic.com](https://app.civic.com)
    2. Click your account name in the bottom left
    3. Go to **[Install → MCP URL](https://app.civic.com/web/install/mcp-url)**
    4. Click **Generate Token** and copy it immediately — it won't be shown again

    <Warning>
      Never commit your token to source control. Store it in environment variables or a secrets manager. Tokens expire after 30 days.
    </Warning>

    ### Set Environment Variables

    ```bash theme={null}
    CIVIC_TOKEN=your-civic-token-here
    CIVIC_URL=https://app.civic.com/hub/mcp
    ```

    For production agents, lock to a specific toolkit by appending a `profile` parameter:

    ```bash theme={null}
    CIVIC_URL=https://app.civic.com/hub/mcp?profile=your-toolkit-alias
    ```

    ### Use the Token

    Pass the token as a Bearer token in the `Authorization` header:

    ```python theme={null}
    headers = {"Authorization": f"Bearer {os.environ['CIVIC_TOKEN']}"}
    ```

    ```typescript theme={null}
    headers: { Authorization: `Bearer ${process.env.CIVIC_TOKEN}` }
    ```

    <Card title="Full credentials guide" icon="key" href="/civic/quickstart/credentials">
      Token generation, URL parameters, OAuth vs token comparison
    </Card>

    ```bash theme={null}
    # .env
    ANTHROPIC_API_KEY=your_anthropic_api_key
    CIVIC_TOKEN=your-civic-token-here
    CIVIC_URL=https://app.civic.com/hub/mcp
    ```
  </Tab>

  <Tab title="Next.js App (Civic Auth)">
    For web apps where each user has their own Civic session — use Civic Auth to exchange the user's session for an access token.

    **Why Civic Auth?** Civic needs to identify which user is accessing tools. Civic Auth provides the per-user access token.

    **Why Civic Auth?** Civic needs to identify which user is accessing tools and authorize their permissions. Civic Auth provides the secure access token. (Support for additional identity providers coming soon.)

    <Tabs>
      <Tab title="1. next.config.ts">
        ```ts theme={null}
        import { createCivicAuthPlugin } from "@civic/auth/nextjs"
        import type { NextConfig } from "next";

        const nextConfig: NextConfig = {};
        const withCivicAuth = createCivicAuthPlugin({ clientId: "YOUR_CLIENT_ID" });
        export default withCivicAuth(nextConfig)
        ```
      </Tab>

      <Tab title="2. API Route">
        **File:** `src/app/api/auth/[...civicauth]/route.ts`

        ```ts theme={null}
        import { handler } from "@civic/auth/nextjs"
        export const GET = handler()
        export const POST = handler()
        ```
      </Tab>

      <Tab title="3. Middleware">
        **File:** `src/middleware.ts`

        ```ts theme={null}
        import { authMiddleware } from "@civic/auth/nextjs/middleware"
        export default authMiddleware();
        export const config = { matcher: ['/((?!_next|favicon.ico|.*\\.png).*)',] };
        ```
      </Tab>

      <Tab title="4. Get Token">
        ```ts theme={null}
        import { getTokens } from "@civic/auth/nextjs";
        const { accessToken } = await getTokens();
        // Use in headers:
        headers: { Authorization: `Bearer ${accessToken}` }
        ```
      </Tab>
    </Tabs>

    <CardGroup cols={2}>
      <Card title="Full Integration Guide" icon="book" href="/integration/nextjs">
        Complete Next.js setup with frontend components, configuration options, and deployment details
      </Card>

      <Card title="AI Prompt for Next.js" icon="robot" href="/ai-prompts/nextjs">
        Use Claude, ChatGPT, or other AI assistants to automatically set up Civic Auth
      </Card>
    </CardGroup>

    <Note>
      Get your Client ID at [auth.civic.com](https://auth.civic.com)
    </Note>

    ```bash theme={null}
    # .env.local
    ANTHROPIC_API_KEY=your_anthropic_api_key
    CIVIC_AUTH_CLIENT_ID=your_client_id  # from auth.civic.com
    ```
  </Tab>
</Tabs>

## Basic Example

<Tabs>
  <Tab title="Backend / Script">
    ```typescript theme={null}
    import Anthropic from '@anthropic-ai/sdk';

    const client = new Anthropic({
      apiKey: process.env.ANTHROPIC_API_KEY!,
    });

    async function createMessage(userMessage: string) {
      const response = await client.messages.create({
        model: 'claude-sonnet-4-5',
        max_tokens: 1024,
        messages: [{ role: 'user', content: userMessage }],
        mcp_servers: [
          {
            type: 'url',
            url: process.env.CIVIC_URL!,
            name: 'civic',
            authorization_token: process.env.CIVIC_TOKEN!,
          },
        ],
      }, {
        headers: {
          'anthropic-beta': 'mcp-client-2025-11-20',
        },
      });

      return response;
    }
    ```
  </Tab>

  <Tab title="Next.js API Route">
    ```typescript theme={null}
    // app/api/chat/route.ts
    import { NextRequest, NextResponse } from 'next/server';
    import Anthropic from '@anthropic-ai/sdk';
    import { getTokens } from '@civic/auth/nextjs';

    const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY! });

    export async function POST(req: NextRequest) {
      const { messages } = await req.json();
      const { accessToken } = await getTokens();
      // getTokens() exchanges the user's Civic Auth session for a hub access token

      if (!accessToken) {
        return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
      }

      const response = await client.messages.create({
        model: 'claude-sonnet-4-5',
        max_tokens: 4096,
        messages,
        mcp_servers: [
          {
            type: 'url',
            url: 'https://app.civic.com/hub/mcp',
            name: 'civic',
            authorization_token: accessToken,
          },
        ],
      }, {
        headers: { 'anthropic-beta': 'mcp-client-2025-11-20' },
      });

      return NextResponse.json(response);
    }
    ```
  </Tab>
</Tabs>

**Key points:**

* Add `mcp_servers` to your `messages.create()` call
* Include the beta header: `"anthropic-beta": "mcp-client-2025-11-20"` (required)
* Pass your token as `authorization_token`
* Claude handles tool selection and execution automatically

## Streaming

```typescript theme={null}
const stream = await client.messages.create({
  model: 'claude-sonnet-4-5',
  max_tokens: 4096,
  messages: [{ role: 'user', content: 'List my GitHub repositories' }],
  mcp_servers: [
    {
      type: 'url',
      url: process.env.CIVIC_URL!,
      name: 'civic',
      authorization_token: process.env.CIVIC_TOKEN!,
    },
  ],
  stream: true,
}, {
  headers: { 'anthropic-beta': 'mcp-client-2025-11-20' },
});

for await (const event of stream) {
  if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {
    process.stdout.write(event.delta.text);
  }
}
```

## Tool Configuration (Optional)

Restrict which tools Claude can use:

```typescript theme={null}
mcp_servers: [
  {
    type: 'url',
    url: process.env.CIVIC_URL!,
    name: 'civic',
    authorization_token: process.env.CIVIC_TOKEN!,
    tool_configuration: {
      enabled: true,
      allowed_tools: ['github__list_repos', 'slack__search_messages']
    }
  },
]
```

## Current Limitations

<Note>
  The MCP connector currently only supports:

  * Tool calls (not MCP resources or prompts)
  * HTTP servers (not STDIO servers)
  * SSE and Streamable HTTP transports

  Amazon Bedrock and Google Vertex integrations are not yet supported.
</Note>

## Comparison

| Feature              | Anthropic MCP Connector | OpenAI Agents SDK | Vercel AI SDK |
| -------------------- | ----------------------- | ----------------- | ------------- |
| **Setup Complexity** | Low                     | Low               | Medium        |
| **MCP SDK Needed**   | No                      | No                | Yes           |
| **Tool Looping**     | No (automatic)          | No (automatic)    | Yes (manual)  |
| **Best For**         | Direct API usage        | Quick prototypes  | Next.js apps  |
| **Streaming**        | Yes                     | Yes               | Yes           |

## Next Steps

<CardGroup cols={2}>
  <Card title="Anthropic MCP Docs" icon="message" href="https://docs.anthropic.com/en/docs/agents-and-tools/mcp-connector">
    Official Anthropic MCP connector reference
  </Card>

  <Card title="Get Help" icon="slack" href="https://join.slack.com/t/civic-developers/shared_invite/zt-37tv9fyo7-aDT43mUjOFQwdQFmfZLTRw">
    Developer Slack
  </Card>
</CardGroup>
