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

# MCP Servers

> Extend your agent with external tools via Model Context Protocol

## What are MCP Servers?

**MCP Servers** are remote services that provide additional tools to your agent using the Model Context Protocol (MCP). Instead of building every tool from scratch, you can connect to existing MCP servers that provide database queries, web searches, documentation access, and more.

<Card title="Think of it as:" icon="plug">
  Plug-and-play extensions for your agent - connect to pre-built tools without writing code
</Card>

<Note>
  **What is MCP?** The Model Context Protocol is an open standard developed by Anthropic for connecting AI models to external tools and data sources. Learn more at [modelcontextprotocol.io](https://modelcontextprotocol.io).
</Note>

## Why MCP Servers?

<CardGroup cols={2}>
  <Card title="No Code Required" icon="magic-wand-sparkles">
    Use existing MCP servers - just configure and connect
  </Card>

  <Card title="Open Standard" icon="lock-open">
    MCP is an open protocol with a growing ecosystem
  </Card>

  <Card title="Extend Capabilities" icon="puzzle-piece">
    Add databases, web search, documentation access, and more
  </Card>

  <Card title="Mix & Match" icon="layer-group">
    Combine MCP servers with your custom LuaSkills
  </Card>
</CardGroup>

## How MCP Servers Work

<Steps>
  <Step title="Configure Server">
    Define the MCP server in your code with transport and connection details
  </Step>

  <Step title="Compile & Push">
    Run `lua compile` and `lua push mcp` to register with the platform
  </Step>

  <Step title="Activate">
    Activate the server to make its tools available to your agent
  </Step>

  <Step title="Agent Uses Tools">
    Your agent automatically discovers and uses the MCP server's tools
  </Step>
</Steps>

## Transport Types

MCP servers connect via HTTP-based transports:

<Tabs>
  <Tab title="Streamable HTTP (Recommended)">
    **Modern MCP standard - Best for most use cases**

    * Single endpoint for bidirectional communication
    * Supports session management and resumability
    * Works with all modern MCP servers

    ```typescript theme={null}
    import { LuaMCPServer, env } from 'lua-cli';

    const docsServer = new LuaMCPServer({
      name: 'docs',
      transport: 'streamable-http',
      url: 'https://mcp.example.com/mcp',
      headers: () => ({ 
        'Authorization': `Bearer ${env("MCP_API_TOKEN")}` 
      })
    });
    ```
  </Tab>

  <Tab title="SSE (Legacy)">
    **For older MCP servers that don't support Streamable HTTP**

    * Uses Server-Sent Events for server-to-client streaming
    * Separate endpoints for requests and events
    * Use when connecting to legacy MCP services

    ```typescript theme={null}
    import { LuaMCPServer, env } from 'lua-cli';

    const legacyServer = new LuaMCPServer({
      name: 'legacy-api',
      transport: 'sse',
      url: 'https://old-mcp.example.com/sse',
      headers: () => ({ 
        'Authorization': `Bearer ${env("API_KEY")}` 
      })
    });
    ```
  </Tab>
</Tabs>

<Warning>
  **stdio transport not supported yet**: Local MCP servers (using `npx`, `node`, etc.) are not supported yet.
  Please use remote MCP servers with `streamable-http` or `sse` transport instead.
</Warning>

## Simple Example

```typescript theme={null}
import { LuaAgent, LuaMCPServer, LuaSkill, env } from 'lua-cli';

// Connect to a remote MCP server
const docsServer = new LuaMCPServer({
  name: 'docs',
  transport: 'streamable-http',
  url: 'https://docs.example.com/mcp',
  headers: () => ({
    'Authorization': `Bearer ${env("DOCS_API_KEY")}`
  })
});

// Your custom skill
const coreSkill = new LuaSkill({
  name: 'core-skill',
  description: 'Core tools',
  tools: [...]
});

export const agent = new LuaAgent({
  name: 'docs-assistant',
  persona: 'You are a helpful assistant with access to documentation.',
  skills: [coreSkill],
  
  // Add MCP server
  mcpServers: [docsServer]
});
```

## Common Use Cases

<Tabs>
  <Tab title="Documentation">
    **Access documentation and knowledge bases**

    ```typescript theme={null}
    import { LuaMCPServer, env } from 'lua-cli';

    const docsServer = new LuaMCPServer({
      name: 'docs',
      transport: 'streamable-http',
      url: 'https://docs.example.com/mcp',
      headers: () => ({
        'Authorization': `Bearer ${env("DOCS_API_KEY")}`
      })
    });
    ```

    Tools provided vary by server:

    * `search_docs` - Search documentation
    * `get_page` - Get specific page content
    * `list_sections` - Browse documentation structure
  </Tab>

  <Tab title="APIs">
    **Connect to API services**

    ```typescript theme={null}
    import { LuaMCPServer, env } from 'lua-cli';

    const apiServer = new LuaMCPServer({
      name: 'my-api',
      transport: 'streamable-http',
      url: 'https://api.example.com/mcp',
      headers: () => ({
        'Authorization': `Bearer ${env("API_KEY")}`,
        'X-Api-Version': '2024-01'
      })
    });
    ```

    Connect to any MCP-compatible API service.
  </Tab>

  <Tab title="Databases">
    **Query hosted database services**

    ```typescript theme={null}
    import { LuaMCPServer, env } from 'lua-cli';

    const dbServer = new LuaMCPServer({
      name: 'database',
      transport: 'streamable-http',
      url: 'https://db-mcp.example.com/mcp',
      headers: () => ({
        'Authorization': `Bearer ${env("DB_API_KEY")}`
      })
    });
    ```

    Tools provided vary by server:

    * `query` - Execute queries
    * `list_tables` - Show tables
    * `describe_table` - Show schema
  </Tab>

  <Tab title="Search">
    **Web and content search**

    ```typescript theme={null}
    import { LuaMCPServer, env } from 'lua-cli';

    const searchServer = new LuaMCPServer({
      name: 'search',
      transport: 'streamable-http',
      url: 'https://search-mcp.example.com/mcp',
      headers: () => ({
        'X-Api-Key': env("SEARCH_API_KEY")
      })
    });
    ```

    Tools provided vary by server:

    * `web_search` - Search the web
    * `image_search` - Search images
    * `news_search` - Search news
  </Tab>
</Tabs>

## Environment Variables

MCP servers often need API keys or connection strings. Use the `env()` function to securely access environment variables at runtime:

<Tabs>
  <Tab title="Using env() (Recommended)">
    **Resolved at runtime from agent's environment**

    ```typescript theme={null}
    import { LuaMCPServer, env } from 'lua-cli';

    const apiServer = new LuaMCPServer({
      name: 'my-api',
      transport: 'streamable-http',
      url: 'https://api.example.com/mcp',
      headers: () => ({
        'Authorization': `Bearer ${env("API_TOKEN")}`,
        'X-Api-Key': env("API_KEY")
      })
    });
    ```

    * Function is compiled and executed at runtime
    * Values come from `lua env production` settings
    * Consistent with `env()` in tool execute functions
    * **Recommended for secrets and API keys**
  </Tab>

  <Tab title="Static Values">
    **Stored directly in configuration**

    ```typescript theme={null}
    const apiServer = new LuaMCPServer({
      name: 'my-api',
      transport: 'streamable-http',
      url: 'https://api.example.com/mcp',
      headers: { 
        'X-Custom-Header': 'value',
        'Accept': 'application/json'
      }
    });
    ```

    * Values are stored as-is in the database
    * Use only for non-sensitive configuration
    * **Not recommended for secrets**
  </Tab>
</Tabs>

<Note>
  **Setting Environment Variables:** Use `lua env production` to manage your agent's environment variables. These are securely stored and made available to the `env()` function at runtime.
</Note>

### Dynamic URL with env()

You can also use `env()` to resolve the URL at runtime:

```typescript theme={null}
import { LuaMCPServer, env } from 'lua-cli';

const apiServer = new LuaMCPServer({
  name: 'my-api',
  transport: 'streamable-http',
  url: () => env("MCP_SERVER_URL"),
  headers: () => ({
    'Authorization': `Bearer ${env("API_TOKEN")}`
  })
});
```

## MCP vs Custom Skills

| Aspect            | MCP Servers               | LuaSkill              |
| ----------------- | ------------------------- | --------------------- |
| **Code Required** | None (just config)        | Yes (TypeScript)      |
| **Customization** | Limited to server options | Full control          |
| **Availability**  | Growing ecosystem         | Unlimited             |
| **Best For**      | Standard integrations     | Custom business logic |

<Note>
  **Best practice:** Use MCP servers for standard integrations (docs, APIs, databases) and LuaSkill for custom business logic. They work great together!
</Note>

## Lifecycle

MCP servers have a simple lifecycle:

```
Define → Compile → Push → Activate → Use → Deactivate
```

<AccordionGroup>
  <Accordion title="1. Define">
    Create `LuaMCPServer` in your source code
  </Accordion>

  <Accordion title="2. Compile">
    Run `lua compile` - registers server and gets ID
  </Accordion>

  <Accordion title="3. Push">
    Run `lua push mcp` or `lua push all --force` - syncs configuration
  </Accordion>

  <Accordion title="4. Activate">
    Run `lua mcp activate` - makes tools available to agent
  </Accordion>

  <Accordion title="5. Use">
    Agent discovers and uses MCP server tools at runtime
  </Accordion>

  <Accordion title="6. Deactivate">
    Run `lua mcp deactivate` - removes tools from agent
  </Accordion>
</AccordionGroup>

## Managing MCP Servers

Use the `lua mcp` command to manage servers:

```bash theme={null}
lua mcp list        # List all MCP servers and their status
lua mcp activate    # Activate a server (make tools available)
lua mcp deactivate  # Deactivate a server (remove tools)
lua mcp delete      # Delete a server from the platform
```

## Next Steps

<CardGroup cols={2}>
  <Card title="LuaMCPServer API" icon="book" href="/api/luamcpserver">
    Complete API reference and examples
  </Card>

  <Card title="MCP Command" icon="terminal" href="/cli/mcp-command">
    CLI commands for managing servers
  </Card>

  <Card title="LuaAgent" icon="robot" href="/overview/agent">
    Adding MCP servers to your agent
  </Card>

  <Card title="Skills Concept" icon="puzzle-piece" href="/overview/skill">
    Custom tools with LuaSkill
  </Card>

  <Card title="Use Lua with Claude & Cursor" icon="wand-magic-sparkles" href="/mcp-for-builders">
    Connect Lua's docs to your AI coding assistant via MCP
  </Card>
</CardGroup>
