MCP - Chainlit

2 min read Original article ↗

Overview

MCP provides a mechanism for Chainlit applications to connect to either server-sent events (SSE) or streamable HTTP based services, or command-line (stdio) based tools. Once connected, your application can discover available tools, execute them, and integrate their responses into your application’s flow.

Contact us for Enterprise Ready MCP

We’re working with companies to create their MCP stacks, enabling AI agents to consume their data and context in standardized ways. Fill out this form.

Connections Types

Chainlit supports three types of MCP connections:

  1. SSE (Server-Sent Events): Connect to a remote service via HTTP
  2. Streamable HTTP: Send HTTP requests to a server and receive JSON responses or connect using SSE streams
  3. stdio: Execute a local command and communicate via standard I/O
⚠️ Security Warning: The stdio connection type spawns actual subprocesses on the Chainlit server. Only use this with trusted commands in controlled environments. Ensure proper validation of user inputs to prevent command injection vulnerabilities.

Server-Side Configuration (config.toml)

You can control which MCP connection types are enabled globally and restrict allowed stdio commands by modifying your project’s config.toml file (usually located at the root of your project or .chainlit/config.toml). Under the [features.mcp] section, you can configure SSE, Streamable HTTP and stdio separately:

Setup

1. Register Connection Handlers

To use MCP in your Chainlit application, you need to implement the on_mcp_connect handler. The on_mcp_disconnect handler is optional but recommended for proper cleanup.

2. Client Configuration

The client needs to provide the connection details through the Chainlit interface. This includes:

  • Connection name (unique identifier)
  • Client type (sse, streamable-http or stdio)
  • For SSE and Streamable HTTP: URL endpoint
  • For stdio: Full command (e.g., npx your-tool-package or uvx your-tool-package)

Adding an MCP

Working with MCP Connections

Retrieving Available Tools

Upon connection, you can discover the available tools provided by the MCP service:

Executing Tools

You can execute tools using the MCP session:

Integrating with LLMs

MCP tools can be seamlessly integrated with LLMs that support tool calling:

Session Management

MCP connections are managed at the session level. Each WebSocket session can have multiple named MCP connections. The connections are cleaned up when:

  1. The user explicitly disconnects
  2. The same connection name is reused (old connection is replaced)
  3. The WebSocket session ends