diff --git a/docs/first-server/python.mdx b/docs/first-server/python.mdx
deleted file mode 100644
index d48c966..0000000
--- a/docs/first-server/python.mdx
+++ /dev/null
@@ -1,828 +0,0 @@
----
-title: "Python"
-description: "Create a simple MCP server in Python in 15 minutes"
----
-
-Let's build your first MCP server in Python! We'll create a weather server that provides current weather data as a resource and lets Claude fetch forecasts using tools.
-
-
- This guide uses the OpenWeatherMap API. You'll need a free API key from [OpenWeatherMap](https://openweathermap.org/api) to follow along.
-
-
-## Prerequisites
-
-
- The following steps are for macOS. Guides for other platforms are coming soon.
-
-
-
-
- You'll need Python 3.10 or higher:
-
- ```bash
- python --version # Should be 3.10 or higher
- ```
-
-
-
- See https://docs.astral.sh/uv/ for more information.
-
- ```bash
- brew install uv
- uv --version # Should be 0.4.18 or higher
- ```
-
-
-
- ```bash
- uvx create-mcp-server --path weather_service
- cd weather_service
- ```
-
-
-
- ```bash
- uv add httpx python-dotenv
- ```
-
-
-
- Create `.env`:
-
- ```bash
- OPENWEATHER_API_KEY=your-api-key-here
- ```
-
-
-
-## Create your server
-
-
-
- In `weather_service/src/weather_service/server.py`
- ```python
- import os
- import json
- import logging
- from datetime import datetime, timedelta
- from collections.abc import Sequence
- from functools import lru_cache
- from typing import Any
-
- import httpx
- import asyncio
- from dotenv import load_dotenv
- from mcp.server import Server
- from mcp.types import (
- Resource,
- Tool,
- TextContent,
- ImageContent,
- EmbeddedResource,
- LoggingLevel
- )
- from pydantic import AnyUrl
-
- # Load environment variables
- load_dotenv()
-
- # Configure logging
- logging.basicConfig(level=logging.INFO)
- logger = logging.getLogger("weather-server")
-
- # API configuration
- API_KEY = os.getenv("OPENWEATHER_API_KEY")
- if not API_KEY:
- raise ValueError("OPENWEATHER_API_KEY environment variable required")
-
- API_BASE_URL = "http://api.openweathermap.org/data/2.5"
- DEFAULT_CITY = "London"
- CURRENT_WEATHER_ENDPOINT = "weather"
- FORECAST_ENDPOINT = "forecast"
-
- # The rest of our server implementation will go here
- ```
-
-
-
- Add this functionality:
-
- ```python
- # Create reusable params
- http_params = {
- "appid": API_KEY,
- "units": "metric"
- }
-
- async def fetch_weather(city: str) -> dict[str, Any]:
- async with httpx.AsyncClient() as client:
- response = await client.get(
- f"{API_BASE_URL}/weather",
- params={"q": city, **http_params}
- )
- response.raise_for_status()
- data = response.json()
-
- return {
- "temperature": data["main"]["temp"],
- "conditions": data["weather"][0]["description"],
- "humidity": data["main"]["humidity"],
- "wind_speed": data["wind"]["speed"],
- "timestamp": datetime.now().isoformat()
- }
-
-
- app = Server("weather-server")
- ```
-
-
-
- Add these resource-related handlers to our main function:
-
- ```python
- app = Server("weather-server")
-
- @app.list_resources()
- async def list_resources() -> list[Resource]:
- """List available weather resources."""
- uri = AnyUrl(f"weather://{DEFAULT_CITY}/current")
- return [
- Resource(
- uri=uri,
- name=f"Current weather in {DEFAULT_CITY}",
- mimeType="application/json",
- description="Real-time weather data"
- )
- ]
-
- @app.read_resource()
- async def read_resource(uri: AnyUrl) -> str:
- """Read current weather data for a city."""
- city = DEFAULT_CITY
- if str(uri).startswith("weather://") and str(uri).endswith("/current"):
- city = str(uri).split("/")[-2]
- else:
- raise ValueError(f"Unknown resource: {uri}")
-
- try:
- weather_data = await fetch_weather(city)
- return json.dumps(weather_data, indent=2)
- except httpx.HTTPError as e:
- raise RuntimeError(f"Weather API error: {str(e)}")
-
- ```
-
-
-
- Add these tool-related handlers:
-
- ```python
- app = Server("weather-server")
-
- # Resource implementation ...
-
- @app.list_tools()
- async def list_tools() -> list[Tool]:
- """List available weather tools."""
- return [
- Tool(
- name="get_forecast",
- description="Get weather forecast for a city",
- inputSchema={
- "type": "object",
- "properties": {
- "city": {
- "type": "string",
- "description": "City name"
- },
- "days": {
- "type": "number",
- "description": "Number of days (1-5)",
- "minimum": 1,
- "maximum": 5
- }
- },
- "required": ["city"]
- }
- )
- ]
-
- @app.call_tool()
- async def call_tool(name: str, arguments: Any) -> Sequence[TextContent | ImageContent | EmbeddedResource]:
- """Handle tool calls for weather forecasts."""
- if name != "get_forecast":
- raise ValueError(f"Unknown tool: {name}")
-
- if not isinstance(arguments, dict) or "city" not in arguments:
- raise ValueError("Invalid forecast arguments")
-
- city = arguments["city"]
- days = min(int(arguments.get("days", 3)), 5)
-
- try:
- async with httpx.AsyncClient() as client:
- response = await client.get(
- f"{API_BASE_URL}/{FORECAST_ENDPOINT}",
- params={
- "q": city,
- "cnt": days * 8, # API returns 3-hour intervals
- **http_params,
- }
- )
- response.raise_for_status()
- data = response.json()
-
- forecasts = []
- for i in range(0, len(data["list"]), 8):
- day_data = data["list"][i]
- forecasts.append({
- "date": day_data["dt_txt"].split()[0],
- "temperature": day_data["main"]["temp"],
- "conditions": day_data["weather"][0]["description"]
- })
-
- return [
- TextContent(
- type="text",
- text=json.dumps(forecasts, indent=2)
- )
- ]
- except httpx.HTTPError as e:
- logger.error(f"Weather API error: {str(e)}")
- raise RuntimeError(f"Weather API error: {str(e)}")
- ```
-
-
-
- Add this to the end of `weather_service/src/weather_service/server.py`:
-
- ```python
- async def main():
- # Import here to avoid issues with event loops
- from mcp.server.stdio import stdio_server
-
- async with stdio_server() as (read_stream, write_stream):
- await app.run(
- read_stream,
- write_stream,
- app.create_initialization_options()
- )
- ```
-
-
-
- Add this to the end of `weather_service/src/weather_service/__init__.py`:
-
- ```python
- from . import server
- import asyncio
-
- def main():
- """Main entry point for the package."""
- asyncio.run(server.main())
-
- # Optionally expose other important items at package level
- __all__ = ['main', 'server']
- ```
-
-
-
-
-
-
-## Connect to Claude Desktop
-
-
-
- Add to `claude_desktop_config.json`:
-
- ```json
- {
- "mcpServers": {
- "weather": {
- "command": "uv",
- "args": [
- "--directory",
- "path/to/your/project",
- "run",
- "weather-service"
- ],
- "env": {
- "OPENWEATHER_API_KEY": "your-api-key"
- }
- }
- }
- }
- ```
-
-
-
- 1. Quit Claude completely
-
- 2. Start Claude again
-
- 3. Look for your weather server in the π menu
-
-
-
-## Try it out!
-
-
-
- Ask Claude:
-
- ```
- What's the current weather in San Francisco? Can you analyze the conditions and tell me if it's a good day for outdoor activities?
- ```
-
-
-
- Ask Claude:
-
- ```
- Can you get me a 5-day forecast for Tokyo and help me plan what clothes to pack for my trip?
- ```
-
-
-
- Ask Claude:
-
- ```
- Can you analyze the forecast for both Tokyo and San Francisco and tell me which city would be better for outdoor photography this week?
- ```
-
-
-
-## Understanding the code
-
-
-
- ```python
- async def read_resource(self, uri: str) -> ReadResourceResult:
- # ...
- ```
-
- Python type hints help catch errors early and improve code maintainability.
-
-
-
- ```python
- @app.list_resources()
- async def list_resources(self) -> ListResourcesResult:
- return ListResourcesResult(
- resources=[
- Resource(
- uri=f"weather://{DEFAULT_CITY}/current",
- name=f"Current weather in {DEFAULT_CITY}",
- mimeType="application/json",
- description="Real-time weather data"
- )
- ]
- )
- ```
-
- Resources provide data that Claude can access as context.
-
-
-
- ```python
- Tool(
- name="get_forecast",
- description="Get weather forecast for a city",
- inputSchema={
- "type": "object",
- "properties": {
- "city": {
- "type": "string",
- "description": "City name"
- },
- "days": {
- "type": "number",
- "description": "Number of days (1-5)",
- "minimum": 1,
- "maximum": 5
- }
- },
- "required": ["city"]
- }
- )
- ```
-
- Tools let Claude take actions through your server with validated inputs.
-
-
-
- ```python
- # Create server instance with name
- app = Server("weather-server")
-
- # Register resource handler
- @app.list_resources()
- async def list_resources() -> list[Resource]:
- """List available resources"""
- return [...]
-
- # Register tool handler
- @app.call_tool()
- async def call_tool(name: str, arguments: Any) -> Sequence[TextContent]:
- """Handle tool execution"""
- return [...]
-
- # Register additional handlers
- @app.read_resource()
- ...
- @app.list_tools()
- ...
- ```
-
- The MCP server uses a simple app pattern - create a Server instance and register handlers with decorators. Each handler maps to a specific MCP protocol operation.
-
-
-
-## Best practices
-
-
-
- ```python
- try:
- async with httpx.AsyncClient() as client:
- response = await client.get(..., params={..., **http_params})
- response.raise_for_status()
- except httpx.HTTPError as e:
- raise McpError(
- ErrorCode.INTERNAL_ERROR,
- f"API error: {str(e)}"
- )
- ```
-
-
-
- ```python
- if not isinstance(args, dict) or "city" not in args:
- raise McpError(
- ErrorCode.INVALID_PARAMS,
- "Invalid forecast arguments"
- )
- ```
-
-
-
- ```python
- if not API_KEY:
- raise ValueError("OPENWEATHER_API_KEY is required")
- ```
-
-
-
-
-## Available transports
-
-While this guide uses stdio transport, MCP supports additional transport options:
-
-### SSE (Server-Sent Events)
-
-```python
-from mcp.server.sse import SseServerTransport
-from starlette.applications import Starlette
-from starlette.routing import Route
-
-# Create SSE transport with endpoint
-sse = SseServerTransport("/messages")
-
-# Handler for SSE connections
-async def handle_sse(scope, receive, send):
- async with sse.connect_sse(scope, receive, send) as streams:
- await app.run(
- streams[0], streams[1], app.create_initialization_options()
- )
-
-# Handler for client messages
-async def handle_messages(scope, receive, send):
- await sse.handle_post_message(scope, receive, send)
-
-# Create Starlette app with routes
-app = Starlette(
- debug=True,
- routes=[
- Route("/sse", endpoint=handle_sse),
- Route("/messages", endpoint=handle_messages, methods=["POST"]),
- ],
-)
-
-# Run with any ASGI server
-import uvicorn
-uvicorn.run(app, host="0.0.0.0", port=8000)
-```
-
-## Advanced features
-
-
-
- The request context provides access to the current request's metadata and the active client session. Access it through `server.request_context`:
-
- ```python
- @app.call_tool()
- async def call_tool(name: str, arguments: Any) -> Sequence[TextContent]:
- # Access the current request context
- ctx = self.request_context
-
- # Get request metadata like progress tokens
- if progress_token := ctx.meta.progressToken:
- # Send progress notifications via the session
- await ctx.session.send_progress_notification(
- progress_token=progress_token,
- progress=0.5,
- total=1.0
- )
-
- # Sample from the LLM client
- result = await ctx.session.create_message(
- messages=[
- SamplingMessage(
- role="user",
- content=TextContent(
- type="text",
- text="Analyze this weather data: " + json.dumps(arguments)
- )
- )
- ],
- max_tokens=100
- )
-
- return [TextContent(type="text", text=result.content.text)]
- ```
-
-
-
- ```python
- # Cache settings
- cache_timeout = timedelta(minutes=15)
- last_cache_time = None
- cached_weather = None
-
- async def fetch_weather(city: str) -> dict[str, Any]:
- global cached_weather, last_cache_time
-
- now = datetime.now()
- if (cached_weather is None or
- last_cache_time is None or
- now - last_cache_time > cache_timeout):
-
- async with httpx.AsyncClient() as client:
- response = await client.get(
- f"{API_BASE_URL}/{CURRENT_WEATHER_ENDPOINT}",
- params={"q": city, **http_params}
- )
- response.raise_for_status()
- data = response.json()
-
- cached_weather = {
- "temperature": data["main"]["temp"],
- "conditions": data["weather"][0]["description"],
- "humidity": data["main"]["humidity"],
- "wind_speed": data["wind"]["speed"],
- "timestamp": datetime.now().isoformat()
- }
- last_cache_time = now
-
- return cached_weather
- ```
-
-
-
- ```python
- @self.call_tool()
- async def call_tool(self, name: str, arguments: Any) -> CallToolResult:
- if progress_token := self.request_context.meta.progressToken:
- # Send progress notifications
- await self.request_context.session.send_progress_notification(
- progress_token=progress_token,
- progress=1,
- total=2
- )
-
- # Fetch data...
-
- await self.request_context.session.send_progress_notification(
- progress_token=progress_token,
- progress=2,
- total=2
- )
-
- # Rest of the method implementation...
- ```
-
-
-
- ```python
- # Set up logging
- logger = logging.getLogger("weather-server")
- logger.setLevel(logging.INFO)
-
- @app.set_logging_level()
- async def set_logging_level(level: LoggingLevel) -> EmptyResult:
- logger.setLevel(level.upper())
- await app.request_context.session.send_log_message(
- level="info",
- data=f"Log level set to {level}",
- logger="weather-server"
- )
- return EmptyResult()
-
- # Use logger throughout the code
- # For example:
- # logger.info("Weather data fetched successfully")
- # logger.error(f"Error fetching weather data: {str(e)}")
- ```
-
-
-
- ```python
- @app.list_resource_templates()
- async def list_resource_templates() -> list[ResourceTemplate]:
- return [
- ResourceTemplate(
- uriTemplate="weather://{city}/current",
- name="Current weather for any city",
- mimeType="application/json"
- )
- ]
- ```
-
-
-
-## Testing
-
-
-
- Create `tests/weather_test.py`:
-
- ```python
- import pytest
- import os
- from unittest.mock import patch, Mock
- from datetime import datetime
- import json
- from pydantic import AnyUrl
- os.environ["OPENWEATHER_API_KEY"] = "TEST"
-
- from weather_service.server import (
- fetch_weather,
- read_resource,
- call_tool,
- list_resources,
- list_tools,
- DEFAULT_CITY
- )
-
- @pytest.fixture
- def anyio_backend():
- return "asyncio"
-
- @pytest.fixture
- def mock_weather_response():
- return {
- "main": {
- "temp": 20.5,
- "humidity": 65
- },
- "weather": [
- {"description": "scattered clouds"}
- ],
- "wind": {
- "speed": 3.6
- }
- }
-
- @pytest.fixture
- def mock_forecast_response():
- return {
- "list": [
- {
- "dt_txt": "2024-01-01 12:00:00",
- "main": {"temp": 18.5},
- "weather": [{"description": "sunny"}]
- },
- {
- "dt_txt": "2024-01-02 12:00:00",
- "main": {"temp": 17.2},
- "weather": [{"description": "cloudy"}]
- }
- ]
- }
-
- @pytest.mark.anyio
- async def test_fetch_weather(mock_weather_response):
- with patch('requests.Session.get') as mock_get:
- mock_get.return_value.json.return_value = mock_weather_response
- mock_get.return_value.raise_for_status = Mock()
-
- weather = await fetch_weather("London")
-
- assert weather["temperature"] == 20.5
- assert weather["conditions"] == "scattered clouds"
- assert weather["humidity"] == 65
- assert weather["wind_speed"] == 3.6
- assert "timestamp" in weather
-
- @pytest.mark.anyio
- async def test_read_resource():
- with patch('weather_service.server.fetch_weather') as mock_fetch:
- mock_fetch.return_value = {
- "temperature": 20.5,
- "conditions": "clear sky",
- "timestamp": datetime.now().isoformat()
- }
-
- uri = AnyUrl("weather://London/current")
- result = await read_resource(uri)
-
- assert isinstance(result, str)
- assert "temperature" in result
- assert "clear sky" in result
-
- @pytest.mark.anyio
- async def test_call_tool(mock_forecast_response):
- class Response():
- def raise_for_status(self):
- pass
-
- def json(self):
- return mock_forecast_response
-
- class AsyncClient():
- async def __aenter__(self):
- return self
-
- async def __aexit__(self, *exc_info):
- pass
-
- async def get(self, *args, **kwargs):
- return Response()
-
- with patch('httpx.AsyncClient', new=AsyncClient) as mock_client:
- result = await call_tool("get_forecast", {"city": "London", "days": 2})
-
- assert len(result) == 1
- assert result[0].type == "text"
- forecast_data = json.loads(result[0].text)
- assert len(forecast_data) == 1
- assert forecast_data[0]["temperature"] == 18.5
- assert forecast_data[0]["conditions"] == "sunny"
-
- @pytest.mark.anyio
- async def test_list_resources():
- resources = await list_resources()
- assert len(resources) == 1
- assert resources[0].name == f"Current weather in {DEFAULT_CITY}"
- assert resources[0].mimeType == "application/json"
-
- @pytest.mark.anyio
- async def test_list_tools():
- tools = await list_tools()
- assert len(tools) == 1
- assert tools[0].name == "get_forecast"
- assert "city" in tools[0].inputSchema["properties"]
- ```
-
-
- ```bash
- uv add --dev pytest
- uv run pytest
- ```
-
-
-
-## Troubleshooting
-
-### Installation issues
-
-```bash
-# Check Python version
-python --version
-
-# Reinstall dependencies
-uv sync --reinstall
-```
-
-### Type checking
-
-```bash
-# Install mypy
-uv add --dev pyright
-
-# Run type checker
-uv run pyright src
-```
-
-## Next steps
-
-
-
- Learn more about the MCP architecture
-
-
-
- Check out the Python SDK on GitHub
-
-
diff --git a/docs/first-server/typescript.mdx b/docs/first-server/typescript.mdx
deleted file mode 100644
index 0f39531..0000000
--- a/docs/first-server/typescript.mdx
+++ /dev/null
@@ -1,599 +0,0 @@
----
-title: "TypeScript"
-description: "Create a simple MCP server in TypeScript in 15 minutes"
----
-
-Let's build your first MCP server in TypeScript! We'll create a weather server that provides current weather data as a resource and lets Claude fetch forecasts using tools.
-
-
-This guide uses the OpenWeatherMap API. You'll need a free API key from [OpenWeatherMap](https://openweathermap.org/api) to follow along.
-
-
-## Prerequisites
-
-
-
- You'll need Node.js 18 or higher:
-
- ```bash
- node --version # Should be v18 or higher
- npm --version
- ```
-
-
-
- You can use our [create-typescript-server](https://github.com/modelcontextprotocol/create-typescript-server) tool to bootstrap a new project:
-
- ```bash
- npx @modelcontextprotocol/create-server weather-server
- cd weather-server
- ```
-
-
-
- ```bash
- npm install --save axios dotenv
- ```
-
-
-
- Create `.env`:
- ```bash
- OPENWEATHER_API_KEY=your-api-key-here
- ```
- Make sure to add your environment file to `.gitignore`
- ```bash
- .env
- ```
-
-
-
-## Create your server
-
-
-
- Create a file `src/types.ts`, and add the following:
-
- ```typescript
- export interface OpenWeatherResponse {
- main: {
- temp: number;
- humidity: number;
- };
- weather: Array<{
- description: string;
- }>;
- wind: {
- speed: number;
- };
- dt_txt?: string;
- }
-
- export interface WeatherData {
- temperature: number;
- conditions: string;
- humidity: number;
- wind_speed: number;
- timestamp: string;
- }
-
- export interface ForecastDay {
- date: string;
- temperature: number;
- conditions: string;
- }
-
- export interface GetForecastArgs {
- city: string;
- days?: number;
- }
-
- // Type guard for forecast arguments
- export function isValidForecastArgs(args: any): args is GetForecastArgs {
- return (
- typeof args === "object" &&
- args !== null &&
- "city" in args &&
- typeof args.city === "string" &&
- (args.days === undefined || typeof args.days === "number")
- );
- }
- ```
-
-
-
- Replace `src/index.ts` with the following:
-
- ```typescript
- #!/usr/bin/env node
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
- import {
- ListResourcesRequestSchema,
- ReadResourceRequestSchema,
- ListToolsRequestSchema,
- CallToolRequestSchema,
- ErrorCode,
- McpError
- } from "@modelcontextprotocol/sdk/types.js";
- import axios from "axios";
- import dotenv from "dotenv";
- import {
- WeatherData,
- ForecastDay,
- OpenWeatherResponse,
- isValidForecastArgs
- } from "./types.js";
-
- dotenv.config();
-
- const API_KEY = process.env.OPENWEATHER_API_KEY;
- if (!API_KEY) {
- throw new Error("OPENWEATHER_API_KEY environment variable is required");
- }
-
- const API_CONFIG = {
- BASE_URL: 'http://api.openweathermap.org/data/2.5',
- DEFAULT_CITY: 'San Francisco',
- ENDPOINTS: {
- CURRENT: 'weather',
- FORECAST: 'forecast'
- }
- } as const;
-
- class WeatherServer {
- private server: Server;
- private axiosInstance;
-
- constructor() {
- this.server = new Server({
- name: "example-weather-server",
- version: "0.1.0"
- }, {
- capabilities: {
- resources: {},
- tools: {}
- }
- });
-
- // Configure axios with defaults
- this.axiosInstance = axios.create({
- baseURL: API_CONFIG.BASE_URL,
- params: {
- appid: API_KEY,
- units: "metric"
- }
- });
-
- this.setupHandlers();
- this.setupErrorHandling();
- }
-
- private setupErrorHandling(): void {
- this.server.onerror = (error) => {
- console.error("[MCP Error]", error);
- };
-
- process.on('SIGINT', async () => {
- await this.server.close();
- process.exit(0);
- });
- }
-
- private setupHandlers(): void {
- this.setupResourceHandlers();
- this.setupToolHandlers();
- }
-
- private setupResourceHandlers(): void {
- // Implementation continues in next section
- }
-
- private setupToolHandlers(): void {
- // Implementation continues in next section
- }
-
- async run(): Promise {
- const transport = new StdioServerTransport();
- await this.server.connect(transport);
-
- // Although this is just an informative message, we must log to stderr,
- // to avoid interfering with MCP communication that happens on stdout
- console.error("Weather MCP server running on stdio");
- }
- }
-
- const server = new WeatherServer();
- server.run().catch(console.error);
- ```
-
-
-
- Add this to the `setupResourceHandlers` method:
-
- ```typescript
- private setupResourceHandlers(): void {
- this.server.setRequestHandler(
- ListResourcesRequestSchema,
- async () => ({
- resources: [{
- uri: `weather://${API_CONFIG.DEFAULT_CITY}/current`,
- name: `Current weather in ${API_CONFIG.DEFAULT_CITY}`,
- mimeType: "application/json",
- description: "Real-time weather data including temperature, conditions, humidity, and wind speed"
- }]
- })
- );
-
- this.server.setRequestHandler(
- ReadResourceRequestSchema,
- async (request) => {
- const city = API_CONFIG.DEFAULT_CITY;
- if (request.params.uri !== `weather://${city}/current`) {
- throw new McpError(
- ErrorCode.InvalidRequest,
- `Unknown resource: ${request.params.uri}`
- );
- }
-
- try {
- const response = await this.axiosInstance.get(
- API_CONFIG.ENDPOINTS.CURRENT,
- {
- params: { q: city }
- }
- );
-
- const weatherData: WeatherData = {
- temperature: response.data.main.temp,
- conditions: response.data.weather[0].description,
- humidity: response.data.main.humidity,
- wind_speed: response.data.wind.speed,
- timestamp: new Date().toISOString()
- };
-
- return {
- contents: [{
- uri: request.params.uri,
- mimeType: "application/json",
- text: JSON.stringify(weatherData, null, 2)
- }]
- };
- } catch (error) {
- if (axios.isAxiosError(error)) {
- throw new McpError(
- ErrorCode.InternalError,
- `Weather API error: ${error.response?.data.message ?? error.message}`
- );
- }
- throw error;
- }
- }
- );
- }
- ```
-
-
-
- Add these handlers to the `setupToolHandlers` method:
-
- ```typescript
- private setupToolHandlers(): void {
- this.server.setRequestHandler(
- ListToolsRequestSchema,
- async () => ({
- tools: [{
- name: "get_forecast",
- description: "Get weather forecast for a city",
- inputSchema: {
- type: "object",
- properties: {
- city: {
- type: "string",
- description: "City name"
- },
- days: {
- type: "number",
- description: "Number of days (1-5)",
- minimum: 1,
- maximum: 5
- }
- },
- required: ["city"]
- }
- }]
- })
- );
-
- this.server.setRequestHandler(
- CallToolRequestSchema,
- async (request) => {
- if (request.params.name !== "get_forecast") {
- throw new McpError(
- ErrorCode.MethodNotFound,
- `Unknown tool: ${request.params.name}`
- );
- }
-
- if (!isValidForecastArgs(request.params.arguments)) {
- throw new McpError(
- ErrorCode.InvalidParams,
- "Invalid forecast arguments"
- );
- }
-
- const city = request.params.arguments.city;
- const days = Math.min(request.params.arguments.days || 3, 5);
-
- try {
- const response = await this.axiosInstance.get<{
- list: OpenWeatherResponse[]
- }>(API_CONFIG.ENDPOINTS.FORECAST, {
- params: {
- q: city,
- cnt: days * 8 // API returns 3-hour intervals
- }
- });
-
- const forecasts: ForecastDay[] = [];
- for (let i = 0; i < response.data.list.length; i += 8) {
- const dayData = response.data.list[i];
- forecasts.push({
- date: dayData.dt_txt?.split(' ')[0] ?? new Date().toISOString().split('T')[0],
- temperature: dayData.main.temp,
- conditions: dayData.weather[0].description
- });
- }
-
- return {
- content: [{
- type: "text",
- text: JSON.stringify(forecasts, null, 2)
- }]
- };
- } catch (error) {
- if (axios.isAxiosError(error)) {
- return {
- content: [{
- type: "text",
- text: `Weather API error: ${error.response?.data.message ?? error.message}`
- }],
- isError: true,
- }
- }
- throw error;
- }
- }
- );
- }
- ```
-
-
-
- ```bash
- npm run build
- ```
-
-
-
-## Connect to Claude Desktop
-
-
-
- If you didn't already connect to Claude Desktop during project setup, add to `claude_desktop_config.json`:
-
- ```json
- {
- "mcpServers": {
- "weather": {
- "command": "node",
- "args": ["/path/to/weather-server/build/index.js"],
- "env": {
- "OPENWEATHER_API_KEY": "your-api-key",
- }
- }
- }
- }
- ```
-
-
-
- 1. Quit Claude completely
- 2. Start Claude again
- 3. Look for your weather server in the π menu
-
-
-
-## Try it out!
-
-
-
- Ask Claude:
- ```
- What's the current weather in San Francisco? Can you analyze the conditions?
- ```
-
-
-
- Ask Claude:
- ```
- Can you get me a 5-day forecast for Tokyo and tell me if I should pack an umbrella?
- ```
-
-
-
- Ask Claude:
- ```
- Can you analyze the forecast for both Tokyo and San Francisco and tell me which city will be warmer this week?
- ```
-
-
-
-## Understanding the code
-
-
-
- ```typescript
- interface WeatherData {
- temperature: number;
- conditions: string;
- humidity: number;
- wind_speed: number;
- timestamp: string;
- }
- ```
- TypeScript adds type safety to our MCP server, making it more reliable and easier to maintain.
-
-
-
- ```typescript
- this.server.setRequestHandler(
- ListResourcesRequestSchema,
- async () => ({
- resources: [{
- uri: `weather://${DEFAULT_CITY}/current`,
- name: `Current weather in ${DEFAULT_CITY}`,
- mimeType: "application/json"
- }]
- })
- );
- ```
- Resources provide data that Claude can access as context.
-
-
-
- ```typescript
- {
- name: "get_forecast",
- description: "Get weather forecast for a city",
- inputSchema: {
- type: "object",
- properties: {
- city: { type: "string" },
- days: { type: "number" }
- }
- }
- }
- ```
- Tools let Claude take actions through your server with type-safe inputs.
-
-
-
-## Best practices
-
-
-
- When a tool encounters an error, return the error message with `isError: true`, so the model can self-correct:
-
- ```typescript
- try {
- const response = await axiosInstance.get(...);
- } catch (error) {
- if (axios.isAxiosError(error)) {
- return {
- content: {
- mimeType: "text/plain",
- text: `Weather API error: ${error.response?.data.message ?? error.message}`
- },
- isError: true,
- }
- }
- throw error;
- }
- ```
-
- For other handlers, throw an error, so the application can notify the user:
-
- ```typescript
- try {
- const response = await this.axiosInstance.get(...);
- } catch (error) {
- if (axios.isAxiosError(error)) {
- throw new McpError(
- ErrorCode.InternalError,
- `Weather API error: ${error.response?.data.message}`
- );
- }
- throw error;
- }
- ```
-
-
-
- ```typescript
- function isValidForecastArgs(args: any): args is GetForecastArgs {
- return (
- typeof args === "object" &&
- args !== null &&
- "city" in args &&
- typeof args.city === "string"
- );
- }
- ```
-
- You can also use libraries like [Zod](https://zod.dev/) to perform this validation automatically.
-
-
-
-## Available transports
-
-While this guide uses stdio to run the MCP server as a local process, MCP supports other [transports](/docs/concepts/transports) as well.
-
-## Troubleshooting
-
-
- The following troubleshooting tips are for macOS. Guides for other platforms are coming soon.
-
-
-### Build errors
-```bash
-# Check TypeScript version
-npx tsc --version
-
-# Clean and rebuild
-rm -rf build/
-npm run build
-```
-
-### Runtime errors
-Look for detailed error messages in the Claude Desktop logs:
-```bash
-# Monitor logs
-tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
-```
-
-### Type errors
-```bash
-# Check types without building
-npx tsc --noEmit
-```
-
-## Next steps
-
-
-
- Learn more about the MCP architecture
-
-
-
- Check out the TypeScript SDK on GitHub
-
-
-
-
-Need help? Ask Claude! Since it has access to the MCP SDK documentation, it can help you debug issues and suggest improvements to your server.
-
diff --git a/docs/tools/debugging.mdx b/docs/tools/debugging.mdx
index d2a2ac0..6161a13 100644
--- a/docs/tools/debugging.mdx
+++ b/docs/tools/debugging.mdx
@@ -34,11 +34,11 @@ MCP provides several tools for debugging at different levels:
The Claude.app interface provides basic server status information:
-1. Click the π icon to view:
+1. Click the icon to view:
- Connected servers
- Available prompts and resources
-2. Click the π¨ icon to view:
+2. Click the icon to view:
- Tools made available to the model
### Viewing logs
diff --git a/examples.mdx b/examples.mdx
new file mode 100644
index 0000000..dd02c28
--- /dev/null
+++ b/examples.mdx
@@ -0,0 +1,123 @@
+---
+title: Examples
+description: 'A list of example servers and implementations'
+---
+
+This page showcases various Model Context Protocol (MCP) servers that demonstrate the protocol's capabilities and versatility. These servers enable Large Language Models (LLMs) to securely access tools and data sources.
+
+## Reference implementations
+
+These official reference servers demonstrate core MCP features and SDK usage:
+
+### Data and file systems
+- **[Filesystem](src/filesystem)** - Secure file operations with configurable access controls
+- **[PostgreSQL](src/postgres)** - Read-only database access with schema inspection capabilities
+- **[SQLite](src/sqlite)** - Database interaction and business intelligence features
+- **[Google Drive](src/gdrive)** - File access and search capabilities for Google Drive
+
+### Development tools
+- **[Git](src/git)** - Tools to read, search, and manipulate Git repositories
+- **[GitHub](src/github)** - Repository management, file operations, and GitHub API integration
+- **[GitLab](src/gitlab)** - GitLab API integration enabling project management
+- **[Sentry](src/sentry)** - Retrieving and analyzing issues from Sentry.io
+
+### Web and browser automation
+- **[Brave Search](src/brave-search)** - Web and local search using Brave's Search API
+- **[Fetch](src/fetch)** - Web content fetching and conversion optimized for LLM usage
+- **[Puppeteer](src/puppeteer)** - Browser automation and web scraping capabilities
+
+### Productivity and communication
+- **[Slack](src/slack)** - Channel management and messaging capabilities
+- **[Google Maps](src/google-maps)** - Location services, directions, and place details
+- **[Memory](src/memory)** - Knowledge graph-based persistent memory system
+
+### AI and specialized tools
+- **[EverArt](src/everart)** - AI image generation using various models
+- **[Sequential Thinking](src/sequentialthinking)** - Dynamic problem-solving through thought sequences
+- **[AWS KB Retrieval](src/aws-kb-retrieval)** - Retrieval from AWS Knowledge Base using Bedrock Agent Runtime
+
+## Official integrations
+
+These MCP servers are maintained by companies for their platforms:
+
+- **[Axiom](https://github.com/axiomhq/mcp-server-axiom)** - Query and analyze logs, traces, and event data using natural language
+- **[Browserbase](https://github.com/browserbase/mcp-server-browserbase)** - Automate browser interactions in the cloud
+- **[Cloudflare](https://github.com/cloudflare/mcp-server-cloudflare)** - Deploy and manage resources on the Cloudflare developer platform
+- **[E2B](https://github.com/e2b-dev/mcp-server)** - Execute code in secure cloud sandboxes
+- **[Neon](https://github.com/neondatabase/mcp-server-neon)** - Interact with the Neon serverless Postgres platform
+- **[Obsidian Markdown Notes](https://github.com/calclavia/mcp-obsidian)** - Read and search through Markdown notes in Obsidian vaults
+- **[Qdrant](https://github.com/qdrant/mcp-server-qdrant/)** - Implement semantic memory using the Qdrant vector search engine
+- **[Raygun](https://github.com/MindscapeHQ/mcp-server-raygun)** - Access crash reporting and monitoring data
+- **[Search1API](https://github.com/fatwang2/search1api-mcp)** - Unified API for search, crawling, and sitemaps
+- **[Tinybird](https://github.com/tinybirdco/mcp-tinybird)** - Interface with the Tinybird serverless ClickHouse platform
+
+## Community highlights
+
+A growing ecosystem of community-developed servers extends MCP's capabilities:
+
+- **[Docker](https://github.com/ckreiling/mcp-server-docker)** - Manage containers, images, volumes, and networks
+- **[Kubernetes](https://github.com/Flux159/mcp-server-kubernetes)** - Manage pods, deployments, and services
+- **[Linear](https://github.com/jerhadf/linear-mcp-server)** - Project management and issue tracking
+- **[Snowflake](https://github.com/datawiz168/mcp-snowflake-service)** - Interact with Snowflake databases
+- **[Spotify](https://github.com/varunneal/spotify-mcp)** - Control Spotify playback and manage playlists
+- **[Todoist](https://github.com/abhiz123/todoist-mcp-server)** - Task management integration
+
+> **Note:** Community servers are untested and should be used at your own risk. They are not affiliated with or endorsed by Anthropic.
+
+For a complete list of community servers, visit the [MCP Servers Repository](https://github.com/modelcontextprotocol/servers).
+
+## Getting started
+
+### Using reference servers
+
+TypeScript-based servers can be used directly with `npx`:
+
+```bash
+npx -y @modelcontextprotocol/server-memory
+```
+
+Python-based servers can be used with `uvx` (recommended) or `pip`:
+
+```bash
+# Using uvx
+uvx mcp-server-git
+
+# Using pip
+pip install mcp-server-git
+python -m mcp_server_git
+```
+
+### Configuring with Claude
+
+To use an MCP server with Claude, add it to your configuration:
+
+```json
+{
+ "mcpServers": {
+ "memory": {
+ "command": "npx",
+ "args": ["-y", "@modelcontextprotocol/server-memory"]
+ },
+ "filesystem": {
+ "command": "npx",
+ "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/files"]
+ },
+ "github": {
+ "command": "npx",
+ "args": ["-y", "@modelcontextprotocol/server-github"],
+ "env": {
+ "GITHUB_PERSONAL_ACCESS_TOKEN": ""
+ }
+ }
+ }
+}
+```
+
+## Additional resources
+
+- [MCP Servers Repository](https://github.com/modelcontextprotocol/servers) - Complete collection of reference implementations and community servers
+- [Awesome MCP Servers](https://github.com/punkpeye/awesome-mcp-servers) - Curated list of MCP servers
+- [MCP CLI](https://github.com/wong2/mcp-cli) - Command-line inspector for testing MCP servers
+- [MCP Get](https://mcp-get.com) - Tool for installing and managing MCP servers
+
+Visit our [GitHub Discussions](https://github.com/orgs/modelcontextprotocol/discussions) to engage with the MCP community.
\ No newline at end of file
diff --git a/images/available-mcp-tools.png b/images/available-mcp-tools.png
new file mode 100644
index 0000000..89a2b9c
Binary files /dev/null and b/images/available-mcp-tools.png differ
diff --git a/images/claude-desktop-mcp-hammer-icon.svg b/images/claude-desktop-mcp-hammer-icon.svg
new file mode 100644
index 0000000..d8e4f80
--- /dev/null
+++ b/images/claude-desktop-mcp-hammer-icon.svg
@@ -0,0 +1,3 @@
+
diff --git a/images/claude-desktop-mcp-plug-icon.svg b/images/claude-desktop-mcp-plug-icon.svg
new file mode 100644
index 0000000..1cf5678
--- /dev/null
+++ b/images/claude-desktop-mcp-plug-icon.svg
@@ -0,0 +1,3 @@
+
diff --git a/images/client-claude-cli-python.png b/images/client-claude-cli-python.png
new file mode 100644
index 0000000..0997ebc
Binary files /dev/null and b/images/client-claude-cli-python.png differ
diff --git a/images/current-weather.png b/images/current-weather.png
new file mode 100644
index 0000000..7b440f1
Binary files /dev/null and b/images/current-weather.png differ
diff --git a/images/visual-indicator-mcp-tools.png b/images/visual-indicator-mcp-tools.png
new file mode 100644
index 0000000..af71d07
Binary files /dev/null and b/images/visual-indicator-mcp-tools.png differ
diff --git a/images/weather-alerts.png b/images/weather-alerts.png
new file mode 100644
index 0000000..d234ac5
Binary files /dev/null and b/images/weather-alerts.png differ
diff --git a/introduction.mdx b/introduction.mdx
index 571602e..82a70a6 100644
--- a/introduction.mdx
+++ b/introduction.mdx
@@ -3,53 +3,80 @@ title: Introduction
description: 'Get started with the Model Context Protocol (MCP)'
---
-The Model Context Protocol (MCP) is an open protocol that enables seamless integration between LLM applications and external data sources and tools. Whether you're building an AI-powered IDE, enhancing a chat interface, or creating custom AI workflows, MCP provides a standardized way to connect LLMs with the context they need.
+MCP is an open protocol that standardizes how applications provide context to LLMs. Think of MCP like a USB-C port for AI applications. Just as USB-C provides a standardized way to connect your devices to various peripherals and accessories, MCP provides a standardized way to connect AI models to different data sources and tools.
-## Get started with MCP
+## Why MCP?
+
+MCP helps you build agents and complex workflows on top of LLMs. LLMs frequently need to integrate with data and tools, and MCP provides:
+- A growing list of pre-built integrations that your LLM can directly plug into
+- The flexibility to switch between LLM providers and vendors
+- Best practices for securing your data within your infrastructure
+
+### General architecture
+
+At its core, MCP follows a client-server architecture where a host application can connect to multiple servers:
+
+```mermaid
+flowchart LR
+ subgraph "Your Computer"
+ Host["MCP Host\n(Claude, IDEs, Tools)"]
+ S1["MCP Server A"]
+ S2["MCP Server B"]
+ S3["MCP Server C"]
+ Host <-->|"MCP Protocol"| S1
+ Host <-->|"MCP Protocol"| S2
+ Host <-->|"MCP Protocol"| S3
+ S1 <--> D1[("Local\nData Source A")]
+ S2 <--> D2[("Local\nData Source B")]
+ end
+ subgraph "Internet"
+ S3 <-->|"Web APIs"| D3[("Remote\nService C")]
+ end
+```
+
+- **MCP Hosts**: Programs like Claude Desktop, IDEs, or AI tools that want to access data through MCP
+- **MCP Clients**: Protocol clients that maintain 1:1 connections with servers
+- **MCP Servers**: Lightweight programs that each expose specific capabilities through the standardized Model Context Protocol
+- **Local Data Sources**: Your computer's files, databases, and services that MCP servers can securely access
+- **Remote Services**: External systems available over the internet (e.g., through APIs) that MCP servers can connect to
+
+## Get started
Choose the path that best fits your needs:
-
+
- The fastest way to see MCP in action—connect example servers to Claude Desktop
+ Build and connect to your first MCP server
- Create a simple MCP server in Python to understand the basics
-
-
- Create a simple MCP server in TypeScript to understand the basics
+ Check out our gallery of official MCP servers and implementations
-## Development tools
-
-Essential tools for building and debugging MCP servers:
+## Tutorials
- Learn how to effectively debug MCP servers and integrations
+ title="Building a MCP client"
+ icon="outlet"
+ href="/building-a-client"
+ >
+ Learn how to build your first MCP client
- Test and inspect your MCP servers with our interactive debugging tool
+ Learn how to use Claude to speed up your MCP development
@@ -59,7 +86,7 @@ Dive deeper into MCP's core concepts and capabilities:
@@ -102,6 +129,26 @@ Dive deeper into MCP's core concepts and capabilities:
+## Development tools
+
+Essential tools for building and debugging MCP servers:
+
+
+
+ Learn how to effectively debug MCP servers and integrations
+
+
+ Test and inspect your MCP servers with our interactive debugging tool
+
+
+
## Contributing
-Want to contribute? Check out [@modelcontextprotocol](https://github.com/modelcontextprotocol) on GitHub to join our growing community of developers building with MCP.
+Want to contribute? Check out [@modelcontextprotocol](https://github.com/modelcontextprotocol) on GitHub to join our growing community of developers building with MCP.
\ No newline at end of file
diff --git a/mint.json b/mint.json
index 6e20058..3a9dc52 100644
--- a/mint.json
+++ b/mint.json
@@ -40,15 +40,14 @@
"navigation": [
{
"group": "Get Started",
- "pages": ["introduction", "quickstart", "clients"]
+ "pages": ["introduction", "quickstart", "examples"]
},
{
- "group": "Your First MCP Server",
- "pages": ["docs/first-server/python", "docs/first-server/typescript"]
- },
- {
- "group": "Development Tools",
- "pages": ["docs/tools/debugging", "docs/tools/inspector"]
+ "group": "Tutorials",
+ "pages": [
+ "tutorials/building-a-client",
+ "tutorials/building-mcp-with-claude"
+ ]
},
{
"group": "Concepts",
diff --git a/quickstart.mdx b/quickstart.mdx
index 240d645..65a2097 100644
--- a/quickstart.mdx
+++ b/quickstart.mdx
@@ -1,432 +1,1092 @@
---
title: "Quickstart"
-description: "Get started with MCP in less than 5 minutes"
+description: "Get started with building your first MCP server and connecting it to a host"
---
-MCP is a protocol that enables secure connections between host applications, such as [Claude Desktop](https://claude.ai/download), and local services. In this quickstart guide, you'll learn how to:
+In this tutorial, we'll build a simple MCP weather server and connect it to a host, Claude for Desktop. We'll start with a basic setup, and then progress to more complex use cases.
-- Set up a local SQLite database
-- Connect Claude Desktop to it through MCP
-- Query and analyze your data securely
+### What we'll be building
-
-While this guide focuses on using Claude Desktop as an example MCP host, the protocol is open and can be integrated by any application. IDEs, AI tools, and other software can all use MCP to connect to local integrations in a standardized way.
-
+Many LLMs (including Claude) do not currently have the ability to fetch the forecast and severe weather alerts. Let's use MCP to solve that!
-
-Claude Desktop's MCP support is currently in developer preview and only supports connecting to local MCP servers running on your machine. Remote MCP connections are not yet supported. This integration is only available in the Claude Desktop app, not the Claude web interface (claude.ai).
-
+We'll build a server that exposes two tools: `get-alerts` and `get-forecast`. Then we'll connect the server to an MCP host (in this case, Claude for Desktop):
-## How MCP works
-
-MCP (Model Context Protocol) is an open protocol that enables secure, controlled interactions between AI applications and local or remote resources. Let's break down how it works, then look at how we'll use it in this guide.
-
-### General Architecture
-At its core, MCP follows a client-server architecture where a host application can connect to multiple servers:
-
-```mermaid
-flowchart LR
- subgraph "Your Computer"
- Host["MCP Host\n(Claude, IDEs, Tools)"]
- S1["MCP Server A"]
- S2["MCP Server B"]
- S3["MCP Server C"]
-
- Host <-->|"MCP Protocol"| S1
- Host <-->|"MCP Protocol"| S2
- Host <-->|"MCP Protocol"| S3
-
- S1 <--> R1[("Local\nResource A")]
- S2 <--> R2[("Local\nResource B")]
- end
-
- subgraph "Internet"
- S3 <-->|"Web APIs"| R3[("Remote\nResource C")]
- end
-```
-
-- **MCP Hosts**: Programs like Claude Desktop, IDEs, or AI tools that want to access resources through MCP
-- **MCP Clients**: Protocol clients that maintain 1:1 connections with servers
-- **MCP Servers**: Lightweight programs that each expose specific capabilities through the standardized Model Context Protocol
-- **Local Resources**: Your computer's resources (databases, files, services) that MCP servers can securely access
-- **Remote Resources**: Resources available over the internet (e.g., through APIs) that MCP servers can connect to
-
-### In This Guide
-
-For this quickstart, we'll implement a focused example using SQLite:
-
-```mermaid
-flowchart LR
- subgraph "Your Computer"
- direction LR
- Claude["Claude Desktop"]
- MCP["SQLite MCP Server"]
- DB[(SQLite Database\n~/test.db)]
-
- Claude <-->|"MCP Protocol\n(Queries & Results)"| MCP
- MCP <-->|"Local Access\n(SQL Operations)"| DB
- end
-```
-
-1. Claude Desktop acts as our MCP client
-2. A SQLite MCP Server provides secure database access
-3. Your local SQLite database stores the actual data
-
-The communication between the SQLite MCP server and your local SQLite database happens entirely on your machine—your SQLite database is not exposed to the internet. The Model Context Protocol ensures that Claude Desktop can only perform approved database operations through well-defined interfaces. This gives you a secure way to let Claude analyze and interact with your local data while maintaining complete control over what it can access.
-
-## Prerequisites
-
-- macOS or Windows
-- The latest version of [Claude Desktop](https://claude.ai/download) installed
-- [uv](https://docs.astral.sh/uv/) 0.4.18 or higher (`uv --version` to check)
-- Git (`git --version` to check)
-- SQLite (`sqlite3 --version` to check)
-
-
-
- ```bash
- # Using Homebrew
- brew install uv git sqlite3
-
- # Or download directly:
- # uv: https://docs.astral.sh/uv/
- # Git: https://git-scm.com
- # SQLite: https://www.sqlite.org/download.html
- ```
-
-
- ```powershell
- # Using winget
- winget install --id=astral-sh.uv -e
- winget install git.git sqlite.sqlite
-
- # Or download directly:
- # uv: https://docs.astral.sh/uv/
- # Git: https://git-scm.com
- # SQLite: https://www.sqlite.org/download.html
- ```
-
-
-
-## Installation
-
-
-
-
-
- Let's create a simple SQLite database for testing:
-
- ```bash
- # Create a new SQLite database
- sqlite3 ~/test.db <
-
-
- Open your Claude Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor.
-
- For example, if you have [VS Code](https://code.visualstudio.com/) installed:
-
- ```bash
- code ~/Library/Application\ Support/Claude/claude_desktop_config.json
- ```
-
- Add this configuration (replace YOUR_USERNAME with your actual username):
-
- ```json
- {
- "mcpServers": {
- "sqlite": {
- "command": "uvx",
- "args": ["mcp-server-sqlite", "--db-path", "/Users/YOUR_USERNAME/test.db"]
- }
- }
- }
- ```
-
- This tells Claude Desktop:
- 1. There's an MCP server named "sqlite"
- 2. Launch it by running `uvx mcp-server-sqlite`
- 3. Connect it to your test database
-
- Save the file, and restart **Claude Desktop**.
-
-
-
-
-
-
- Let's create a simple SQLite database for testing:
-
- ```powershell
- # Create a new SQLite database
- $sql = @'
- CREATE TABLE products (
- id INTEGER PRIMARY KEY,
- name TEXT,
- price REAL
- );
-
- INSERT INTO products (name, price) VALUES
- ('Widget', 19.99),
- ('Gadget', 29.99),
- ('Gizmo', 39.99),
- ('Smart Watch', 199.99),
- ('Wireless Earbuds', 89.99),
- ('Portable Charger', 24.99),
- ('Bluetooth Speaker', 79.99),
- ('Phone Stand', 15.99),
- ('Laptop Sleeve', 34.99),
- ('Mini Drone', 299.99),
- ('LED Desk Lamp', 45.99),
- ('Keyboard', 129.99),
- ('Mouse Pad', 12.99),
- ('USB Hub', 49.99),
- ('Webcam', 69.99),
- ('Screen Protector', 9.99),
- ('Travel Adapter', 27.99),
- ('Gaming Headset', 159.99),
- ('Fitness Tracker', 119.99),
- ('Portable SSD', 179.99);
- '@
-
- cd ~
- & sqlite3 test.db $sql
- ```
-
-
-
- Open your Claude Desktop App configuration at `%APPDATA%\Claude\claude_desktop_config.json` in a text editor.
-
- For example, if you have [VS Code](https://code.visualstudio.com/) installed:
-
- ```powershell
- code $env:AppData\Claude\claude_desktop_config.json
- ```
-
- Add this configuration (replace YOUR_USERNAME with your actual username):
-
- ```json
- {
- "mcpServers": {
- "sqlite": {
- "command": "uvx",
- "args": [
- "mcp-server-sqlite",
- "--db-path",
- "C:\\Users\\YOUR_USERNAME\\test.db"
- ]
- }
- }
- }
- ```
-
- This tells Claude Desktop:
- 1. There's an MCP server named "sqlite"
- 2. Launch it by running `uvx mcp-server-sqlite`
- 3. Connect it to your test database
-
- Save the file, and restart **Claude Desktop**.
-
-
-
-
-
-## Test it out
-
-Let's verify everything is working. Try sending this prompt to Claude Desktop:
-
-```
-Can you connect to my SQLite database and tell me what products are available, and their prices?
-```
-
-Claude Desktop will:
-1. Connect to the SQLite MCP server
-2. Query your local database
-3. Format and present the results
-
-
-
+
+
+
+
+
-## What's happening under the hood?
-
-When you interact with Claude Desktop using MCP:
-
-1. **Server Discovery**: Claude Desktop connects to your configured MCP servers on startup
-2. **Protocol Handshake**: When you ask about data, Claude Desktop:
- - Identifies which MCP server can help (sqlite in this case)
- - Negotiates capabilities through the protocol
- - Requests data or actions from the MCP server
-
-3. **Interaction Flow**:
- ```mermaid
- sequenceDiagram
- participant C as Claude Desktop
- participant M as MCP Server
- participant D as SQLite DB
-
- C->>M: Initialize connection
- M-->>C: Available capabilities
-
- C->>M: Query request
- M->>D: SQL query
- D-->>M: Results
- M-->>C: Formatted results
- ```
-
-4. **Security**:
- - MCP servers only expose specific, controlled capabilities
- - MCP servers run locally on your machine, and the resources they access are not exposed to the internet
- - Claude Desktop requires user confirmation for sensitive operations
-
-## Try these examples
-
-Now that MCP is working, try these increasingly powerful examples:
-
-
-
- ```
- What's the average price of all products in the database?
- ```
-
-
- ```
- Can you analyze the price distribution and suggest any pricing optimizations?
- ```
-
-
- ```
- Could you help me design and create a new table for storing customer orders?
- ```
-
-
-
-## Add more capabilities
-
-Want to give Claude Desktop more local integration capabilities? Add these servers to your configuration:
-
- Note that these MCP servers will require [Node.js](https://nodejs.org/en) to be installed on your machine.
+Servers can connect to any client. We've chosen Claude desktop here for simplicity, but we also have guides on [building your own client](/tutorials/building-a-client)
-
-
- Add this to your config to let Claude Desktop read and analyze files:
- ```json
- "filesystem": {
- "command": "npx",
- "args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/YOUR_USERNAME/Desktop"]
+
+ Because servers are locally run, MCP currently only supports desktop hosts. Remote hosts are in active development.
+
+
+### Core MCP Concepts
+
+MCP servers can provide three main types of capabilities:
+
+1. **Resources**: File-like data that can be read by clients (like API responses or file contents)
+2. **Tools**: Functions that can be called by the LLM (with user approval)
+3. **Prompts**: Pre-written templates that help users accomplish specific tasks
+
+This tutorial focuses on tools, but we have intermediate tutorials if you'd like to learn more about Resources and Prompts.
+
+
+
+
+### Prerequisite knowledge
+
+This quickstart assumes you have familiarity with:
+- Python
+- LLMs like Claude
+
+### System requirements
+
+For Python, make sure you have Python 3.9 or higher installed.
+
+### Set up your environment
+
+First, let's install `uv` and set up our Python project and environment:
+
+
+
+```bash MacOS/Linux
+curl -LsSf https://astral.sh/uv/install.sh | sh
+```
+
+```powershell Windows
+powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
+```
+
+
+
+Make sure to restart your terminal afterwards to ensure that the `uv` command gets picked up.
+
+Now, let's create and set up our project:
+
+
+```bash MacOS/Linux
+# Create a new directory for our project
+uv init weather
+cd weather
+
+# Create virtual environment and activate it
+uv venv
+source .venv/bin/activate
+
+# Install dependencies
+uv add mcp httpx
+
+# Remove template file
+rm hello.py
+
+# Create our files
+mkdir -p src/weather
+touch src/weather/__init__.py
+touch src/weather/server.py
+```
+
+```powershell Windows
+# Create a new directory for our project
+uv init weather
+cd weather
+
+# Create virtual environment and activate it
+uv venv
+.venv\Scripts\activate
+
+# Install dependencies
+uv add mcp httpx
+
+# Clean up boilerplate code
+rm hello.py
+
+# Create our files
+md src
+md src\weather
+new-item src\weather\__init__.py
+new-item src\weather\server.py
+```
+
+
+Add this code to `pyproject.toml`:
+
+```toml
+...rest of config
+
+[build-system]
+requires = [ "hatchling",]
+build-backend = "hatchling.build"
+
+[project.scripts]
+weather = "weather:main"
+```
+
+Add this code to `__init__.py`:
+
+```python src/weather/__init__.py
+from . import server
+import asyncio
+
+def main():
+ """Main entry point for the package."""
+ asyncio.run(server.main())
+
+# Optionally expose other important items at package level
+__all__ = ['main', 'server']
+```
+
+Now let's dive into building your server.
+
+## Building your server
+
+### Importing packages
+
+Add these to the top of your `server.py`:
+```python
+from typing import Any
+import asyncio
+import httpx
+from mcp.server.models import InitializationOptions
+import mcp.types as types
+from mcp.server import NotificationOptions, Server
+import mcp.server.stdio
+```
+
+### Setting up the instance
+
+Then initialize the server instance and the base URL for the NWS API:
+
+```python
+NWS_API_BASE = "https://api.weather.gov"
+USER_AGENT = "weather-app/1.0"
+
+server = Server("weather")
+```
+
+### Implementing tool listing
+
+We need to tell clients what tools are available. The `list_tools()` decorator registers this handler:
+
+```python
+@server.list_tools()
+async def handle_list_tools() -> list[types.Tool]:
+ """
+ List available tools.
+ Each tool specifies its arguments using JSON Schema validation.
+ """
+ return [
+ types.Tool(
+ name="get-alerts",
+ description="Get weather alerts for a state",
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "state": {
+ "type": "string",
+ "description": "Two-letter state code (e.g. CA, NY)",
+ },
+ },
+ "required": ["state"],
+ },
+ ),
+ types.Tool(
+ name="get-forecast",
+ description="Get weather forecast for a location",
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "latitude": {
+ "type": "number",
+ "description": "Latitude of the location",
+ },
+ "longitude": {
+ "type": "number",
+ "description": "Longitude of the location",
+ },
+ },
+ "required": ["latitude", "longitude"],
+ },
+ ),
+ ]
+
+```
+
+This defines our two tools: `get-alerts` and `get-forecast`.
+
+### Helper functions
+
+Next, let's add our helper functions for querying and formatting the data from the National Weather Service API:
+
+```python
+async def make_nws_request(client: httpx.AsyncClient, url: str) -> dict[str, Any] | None:
+ """Make a request to the NWS API with proper error handling."""
+ headers = {
+ "User-Agent": USER_AGENT,
+ "Accept": "application/geo+json"
}
- ```
-
-
- Connect Claude Desktop to your PostgreSQL database:
- ```json
- "postgres": {
- "command": "npx",
- "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://localhost/mydb"]
+ try:
+ response = await client.get(url, headers=headers, timeout=30.0)
+ response.raise_for_status()
+ return response.json()
+ except Exception:
+ return None
+
+def format_alert(feature: dict) -> str:
+ """Format an alert feature into a concise string."""
+ props = feature["properties"]
+ return (
+ f"Event: {props.get('event', 'Unknown')}\n"
+ f"Area: {props.get('areaDesc', 'Unknown')}\n"
+ f"Severity: {props.get('severity', 'Unknown')}\n"
+ f"Status: {props.get('status', 'Unknown')}\n"
+ f"Headline: {props.get('headline', 'No headline')}\n"
+ "---"
+ )
+```
+
+### Implementing tool execution
+
+The tool execution handler is responsible for actually executing the logic of each tool. Let's add it:
+
+```python
+@server.call_tool()
+async def handle_call_tool(
+ name: str, arguments: dict | None
+) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
+ """
+ Handle tool execution requests.
+ Tools can fetch weather data and notify clients of changes.
+ """
+ if not arguments:
+ raise ValueError("Missing arguments")
+
+ if name == "get-alerts":
+ state = arguments.get("state")
+ if not state:
+ raise ValueError("Missing state parameter")
+
+ # Convert state to uppercase to ensure consistent format
+ state = state.upper()
+ if len(state) != 2:
+ raise ValueError("State must be a two-letter code (e.g. CA, NY)")
+
+ async with httpx.AsyncClient() as client:
+ alerts_url = f"{NWS_API_BASE}/alerts?area={state}"
+ alerts_data = await make_nws_request(client, alerts_url)
+
+ if not alerts_data:
+ return [types.TextContent(type="text", text="Failed to retrieve alerts data")]
+
+ features = alerts_data.get("features", [])
+ if not features:
+ return [types.TextContent(type="text", text=f"No active alerts for {state}")]
+
+ # Format each alert into a concise string
+ formatted_alerts = [format_alert(feature) for feature in features[:20]] # only take the first 20 alerts
+ alerts_text = f"Active alerts for {state}:\n\n" + "\n".join(formatted_alerts)
+
+ return [
+ types.TextContent(
+ type="text",
+ text=alerts_text
+ )
+ ]
+ elif name == "get-forecast":
+ try:
+ latitude = float(arguments.get("latitude"))
+ longitude = float(arguments.get("longitude"))
+ except (TypeError, ValueError):
+ return [types.TextContent(
+ type="text",
+ text="Invalid coordinates. Please provide valid numbers for latitude and longitude."
+ )]
+
+ # Basic coordinate validation
+ if not (-90 <= latitude <= 90) or not (-180 <= longitude <= 180):
+ return [types.TextContent(
+ type="text",
+ text="Invalid coordinates. Latitude must be between -90 and 90, longitude between -180 and 180."
+ )]
+
+ async with httpx.AsyncClient() as client:
+ # First get the grid point
+ lat_str = f"{latitude}"
+ lon_str = f"{longitude}"
+ points_url = f"{NWS_API_BASE}/points/{lat_str},{lon_str}"
+ points_data = await make_nws_request(client, points_url)
+
+ if not points_data:
+ return [types.TextContent(type="text", text=f"Failed to retrieve grid point data for coordinates: {latitude}, {longitude}. This location may not be supported by the NWS API (only US locations are supported).")]
+
+ # Extract forecast URL from the response
+ properties = points_data.get("properties", {})
+ forecast_url = properties.get("forecast")
+
+ if not forecast_url:
+ return [types.TextContent(type="text", text="Failed to get forecast URL from grid point data")]
+
+ # Get the forecast
+ forecast_data = await make_nws_request(client, forecast_url)
+
+ if not forecast_data:
+ return [types.TextContent(type="text", text="Failed to retrieve forecast data")]
+
+ # Format the forecast periods
+ periods = forecast_data.get("properties", {}).get("periods", [])
+ if not periods:
+ return [types.TextContent(type="text", text="No forecast periods available")]
+
+ # Format each period into a concise string
+ formatted_forecast = []
+ for period in periods:
+ forecast_text = (
+ f"{period.get('name', 'Unknown')}:\n"
+ f"Temperature: {period.get('temperature', 'Unknown')}Β°{period.get('temperatureUnit', 'F')}\n"
+ f"Wind: {period.get('windSpeed', 'Unknown')} {period.get('windDirection', '')}\n"
+ f"{period.get('shortForecast', 'No forecast available')}\n"
+ "---"
+ )
+ formatted_forecast.append(forecast_text)
+
+ forecast_text = f"Forecast for {latitude}, {longitude}:\n\n" + "\n".join(formatted_forecast)
+
+ return [types.TextContent(
+ type="text",
+ text=forecast_text
+ )]
+ else:
+ raise ValueError(f"Unknown tool: {name}")
+```
+
+### Running the server
+
+Finally, implement the main function to run the server:
+
+```python
+async def main():
+ # Run the server using stdin/stdout streams
+ async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
+ await server.run(
+ read_stream,
+ write_stream,
+ InitializationOptions(
+ server_name="weather",
+ server_version="0.1.0",
+ capabilities=server.get_capabilities(
+ notification_options=NotificationOptions(),
+ experimental_capabilities={},
+ ),
+ ),
+ )
+
+# This is needed if you'd like to connect to a custom client
+if __name__ == "__main__":
+ asyncio.run(main())
+```
+
+Your server is complete! Run `uv run src/weather/server.py` to confirm that everything's working.
+
+Let's now test your server from an existing MCP host, Claude for Desktop.
+
+## Testing your server with Claude for Desktop
+
+
+Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/tutorials/building-a-client) tutorial to build an MCP client that connects to the server we just built.
+
+
+First, make sure you have Claude for Desktop installed. [You can install the latest version here.](https://claude.ai/download)
+
+Next, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor.
+
+For example, if you have [VS Code](https://code.visualstudio.com/) installed:
+
+
+
+```bash
+code ~/Library/Application\ Support/Claude/claude_desktop_config.json
+```
+
+
+```powershell
+code $env:AppData\Claude\claude_desktop_config.json
+```
+
+
+
+
+Add this configuration (replace the parent folder path):
+
+
+
+```json Python
+{
+ "mcpServers": {
+ "weather": {
+ "command": "uv",
+ "args": [
+ "--directory",
+ "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather",
+ "run",
+ "weather"
+ ]
+ }
}
- ```
-
-
+}
+```
+
+
+```json Python
+{
+ "mcpServers": {
+ "weather": {
+ "command": "uv",
+ "args": [
+ "--directory",
+ "C:\\ABSOLUTE\PATH\TO\PARENT\FOLDER\weather",
+ "run",
+ "weather"
+ ]
+ }
+ }
+}
+```
+
+
-## More MCP Clients
+This tells Claude for Desktop:
+1. There's an MCP server named "weather"
+2. Launch it by running `uv --directory /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather run weather`
-While this guide demonstrates MCP using Claude Desktop as a client, several other applications support MCP integration:
+Save the file, and restart **Claude for Desktop**.
+
+
+### Prerequisite knowledge
-
-
- A high-performance, multiplayer code editor with built-in MCP support for AI-powered coding assistance
-
+This quickstart assumes you have familiarity with:
+- TypeScript
+- LLMs like Claude
-
- Code intelligence platform featuring MCP integration for enhanced code search and analysis capabilities
-
-
+### System requirements
-Each host application may implement MCP features differently or support different capabilities. Check their respective documentation for specific setup instructions and supported features.
+For TypeScript, make sure you have the latest version of Node installed.
+
+### Set up your environment
+
+First, let's install Node.js and npm if you haven't already. You can download them from [nodejs.org](https://nodejs.org/).
+Verify your Node.js installation:
+```bash
+node --version
+npm --version
+```
+For this tutorial, you'll need Node.js version 16 or higher.
+
+Now, let's create and set up our project:
+
+
+```bash MacOS/Linux
+# Create a new directory for our project
+mkdir weather
+cd weather
+
+# Initialize a new npm project
+npm init -y
+
+# Install dependencies
+npm install @modelcontextprotocol/sdk zod
+npm install -D @types/node typescript
+
+# Create our files
+mkdir src
+touch src/index.ts
+```
+
+```powershell Windows
+# Create a new directory for our project
+md weather
+cd weather
+
+# Initialize a new npm project
+npm init -y
+
+# Install dependencies
+npm install @modelcontextprotocol/sdk zod
+npm install -D @types/node typescript
+
+# Create our files
+md src
+new-item src\index.ts
+```
+
+
+Update your package.json to add type: "module" and a build script:
+
+```json package.json
+{
+ "type": "module",
+ "bin": {
+ "weather": "./build/index.js"
+ },
+ "scripts": {
+ "build": "tsc && node -e \"require('fs').chmodSync('build/index.js', '755')\"",
+ },
+ "files": [
+ "build"
+ ],
+}
+```
+
+Create a `tsconfig.json` in the root of your project:
+
+```json tsconfig.json
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "Node16",
+ "moduleResolution": "Node16",
+ "outDir": "./build",
+ "rootDir": "./src",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true
+ },
+ "include": ["src/**/*"],
+ "exclude": ["node_modules"]
+}
+```
+
+Now let's dive into building your server.
+
+## Building your server
+
+### Importing packages
+
+Add these to the top of your `src/index.ts`:
+
+```typescript
+import { Server } from "@modelcontextprotocol/sdk/server/index.js";
+import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
+import {
+ CallToolRequestSchema,
+ ListToolsRequestSchema,
+} from "@modelcontextprotocol/sdk/types.js";
+import { z } from "zod";
+```
+
+### Setting up the instance
+
+Then initialize the NWS API base URL, validation schemas, and server instance:
+
+```typescript
+const NWS_API_BASE = "https://api.weather.gov";
+const USER_AGENT = "weather-app/1.0";
+
+// Define Zod schemas for validation
+const AlertsArgumentsSchema = z.object({
+ state: z.string().length(2),
+});
+
+const ForecastArgumentsSchema = z.object({
+ latitude: z.number().min(-90).max(90),
+ longitude: z.number().min(-180).max(180),
+});
+
+// Create server instance
+const server = new Server(
+ {
+ name: "weather",
+ version: "1.0.0",
+ },
+ {
+ capabilities: {
+ tools: {},
+ },
+ }
+);
+```
+
+### Implementing tool listing
+
+We need to tell clients what tools are available. This `server.setRequestHandler` call will register this list for us:
+
+```typescript
+// List available tools
+server.setRequestHandler(ListToolsRequestSchema, async () => {
+ return {
+ tools: [
+ {
+ name: "get-alerts",
+ description: "Get weather alerts for a state",
+ inputSchema: {
+ type: "object",
+ properties: {
+ state: {
+ type: "string",
+ description: "Two-letter state code (e.g. CA, NY)",
+ },
+ },
+ required: ["state"],
+ },
+ },
+ {
+ name: "get-forecast",
+ description: "Get weather forecast for a location",
+ inputSchema: {
+ type: "object",
+ properties: {
+ latitude: {
+ type: "number",
+ description: "Latitude of the location",
+ },
+ longitude: {
+ type: "number",
+ description: "Longitude of the location",
+ },
+ },
+ required: ["latitude", "longitude"],
+ },
+ },
+ ],
+ };
+});
+```
+
+This defines our two tools: `get-alerts` and `get-forecast`.
+
+### Helper functions
+
+Next, let's add our helper functions for querying and formatting the data from the National Weather Service API:
+
+```typescript
+// Helper function for making NWS API requests
+async function makeNWSRequest(url: string): Promise {
+ const headers = {
+ "User-Agent": USER_AGENT,
+ Accept: "application/geo+json",
+ };
+
+ try {
+ const response = await fetch(url, { headers });
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+ return (await response.json()) as T;
+ } catch (error) {
+ console.error("Error making NWS request:", error);
+ return null;
+ }
+}
+
+interface AlertFeature {
+ properties: {
+ event?: string;
+ areaDesc?: string;
+ severity?: string;
+ status?: string;
+ headline?: string;
+ };
+}
+
+// Format alert data
+function formatAlert(feature: AlertFeature): string {
+ const props = feature.properties;
+ return [
+ `Event: ${props.event || "Unknown"}`,
+ `Area: ${props.areaDesc || "Unknown"}`,
+ `Severity: ${props.severity || "Unknown"}`,
+ `Status: ${props.status || "Unknown"}`,
+ `Headline: ${props.headline || "No headline"}`,
+ "---",
+ ].join("\n");
+}
+
+interface ForecastPeriod {
+ name?: string;
+ temperature?: number;
+ temperatureUnit?: string;
+ windSpeed?: string;
+ windDirection?: string;
+ shortForecast?: string;
+}
+
+interface AlertsResponse {
+ features: AlertFeature[];
+}
+
+interface PointsResponse {
+ properties: {
+ forecast?: string;
+ };
+}
+
+interface ForecastResponse {
+ properties: {
+ periods: ForecastPeriod[];
+ };
+}
+```
+
+### Implementing tool execution
+
+The tool execution handler is responsible for actually executing the logic of each tool. Let's add it:
+
+```typescript
+// Handle tool execution
+server.setRequestHandler(CallToolRequestSchema, async (request) => {
+ const { name, arguments: args } = request.params;
+
+ try {
+ if (name === "get-alerts") {
+ const { state } = AlertsArgumentsSchema.parse(args);
+ const stateCode = state.toUpperCase();
+
+ const alertsUrl = `${NWS_API_BASE}/alerts?area=${stateCode}`;
+ const alertsData = await makeNWSRequest(alertsUrl);
+
+ if (!alertsData) {
+ return {
+ content: [
+ {
+ type: "text",
+ text: "Failed to retrieve alerts data",
+ },
+ ],
+ };
+ }
+
+ const features = alertsData.features || [];
+ if (features.length === 0) {
+ return {
+ content: [
+ {
+ type: "text",
+ text: `No active alerts for ${stateCode}`,
+ },
+ ],
+ };
+ }
+
+ const formattedAlerts = features.map(formatAlert).slice(0, 20) // only take the first 20 alerts;
+ const alertsText = `Active alerts for ${stateCode}:\n\n${formattedAlerts.join(
+ "\n"
+ )}`;
+
+ return {
+ content: [
+ {
+ type: "text",
+ text: alertsText,
+ },
+ ],
+ };
+ } else if (name === "get-forecast") {
+ const { latitude, longitude } = ForecastArgumentsSchema.parse(args);
+
+ // Get grid point data
+ const pointsUrl = `${NWS_API_BASE}/points/${latitude.toFixed(
+ 4
+ )},${longitude.toFixed(4)}`;
+ const pointsData = await makeNWSRequest(pointsUrl);
+
+ if (!pointsData) {
+ return {
+ content: [
+ {
+ type: "text",
+ text: `Failed to retrieve grid point data for coordinates: ${latitude}, ${longitude}. This location may not be supported by the NWS API (only US locations are supported).`,
+ },
+ ],
+ };
+ }
+
+ const forecastUrl = pointsData.properties?.forecast;
+ if (!forecastUrl) {
+ return {
+ content: [
+ {
+ type: "text",
+ text: "Failed to get forecast URL from grid point data",
+ },
+ ],
+ };
+ }
+
+ // Get forecast data
+ const forecastData = await makeNWSRequest(forecastUrl);
+ if (!forecastData) {
+ return {
+ content: [
+ {
+ type: "text",
+ text: "Failed to retrieve forecast data",
+ },
+ ],
+ };
+ }
+
+ const periods = forecastData.properties?.periods || [];
+ if (periods.length === 0) {
+ return {
+ content: [
+ {
+ type: "text",
+ text: "No forecast periods available",
+ },
+ ],
+ };
+ }
+
+ // Format forecast periods
+ const formattedForecast = periods.map((period: ForecastPeriod) =>
+ [
+ `${period.name || "Unknown"}:`,
+ `Temperature: ${period.temperature || "Unknown"}Β°${
+ period.temperatureUnit || "F"
+ }`,
+ `Wind: ${period.windSpeed || "Unknown"} ${
+ period.windDirection || ""
+ }`,
+ `${period.shortForecast || "No forecast available"}`,
+ "---",
+ ].join("\n")
+ );
+
+ const forecastText = `Forecast for ${latitude}, ${longitude}:\n\n${formattedForecast.join(
+ "\n"
+ )}`;
+
+ return {
+ content: [
+ {
+ type: "text",
+ text: forecastText,
+ },
+ ],
+ };
+ } else {
+ throw new Error(`Unknown tool: ${name}`);
+ }
+ } catch (error) {
+ if (error instanceof z.ZodError) {
+ throw new Error(
+ `Invalid arguments: ${error.errors
+ .map((e) => `${e.path.join(".")}: ${e.message}`)
+ .join(", ")}`
+ );
+ }
+ throw error;
+ }
+});
+```
+
+### Running the server
+
+Finally, implement the main function to run the server:
+
+```typescript
+// Start the server
+async function main() {
+ const transport = new StdioServerTransport();
+ await server.connect(transport);
+ console.error("Weather MCP Server running on stdio");
+}
+
+main().catch((error) => {
+ console.error("Fatal error in main():", error);
+ process.exit(1);
+});
+```
+
+Make sure to run `npm run build` to build your server! This is a very important step in getting your server to connect.
+
+Let's now test your server from an existing MCP host, Claude for Desktop.
+
+## Testing your server with Claude for Desktop
+
+
+Unfortunately, Claude for Desktop is not yet available on Linux. Linux users can proceed to the [Building a client](/tutorials/building-a-client) tutorial for a workaround.
+
+
+First, make sure you have Claude for Desktop installed. [You can install the latest version here.](https://claude.ai/download)
+
+Next, open your Claude for Desktop App configuration at `~/Library/Application Support/Claude/claude_desktop_config.json` in a text editor.
+
+For example, if you have [VS Code](https://code.visualstudio.com/) installed:
+
+
+
+```bash
+code ~/Library/Application\ Support/Claude/claude_desktop_config.json
+```
+
+
+```powershell
+code $env:AppData\Claude\claude_desktop_config.json
+```
+
+
+
+
+Add this configuration (replace the parent folder path):
+
+
+
+
+```json Node
+{
+ "mcpServers": {
+ "weather": {
+ "command": "node",
+ "args": [
+ "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js"
+ ]
+ }
+ }
+}
+```
+
+
+
+
+```json Node
+{
+ "mcpServers": {
+ "weather": {
+ "command": "node",
+ "args": [
+ "C:\\PATH\TO\PARENT\FOLDER\weather\build\index.js"
+ ]
+ }
+ }
+}
+```
+
+
+
+
+This tells Claude for Desktop:
+1. There's an MCP server named "weather"
+2. Launch it by running `node /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js`
+
+Save the file, and restart **Claude for Desktop**.
+
+
+
+### Test with commands
+
+First, make sure Claude for Desktop is picking up the two tools we've exposed in our `weather` server. You can do this by looking for the hammer icon:
+
+
+
+
+
+After clicking on the hammer icon, you should see two tools listed:
+
+
+
+
+
+If your server isn't being picked up by Claude for Desktop, proceed to the [Troubleshooting](#troubleshooting) section for debugging advice.
+
+You can now test your server by running the following commands in Claude for Desktop:
+
+- What's the weather in Sacramento?
+- What are the active weather alerts in Texas?
+
+
+
+
+
+
+
+
+
+Since this is the US National Weather service, the queries will only work for US locations.
+
+
+## What's happening under the hood
+
+When you ask a question:
+
+1. The client sends your question to Claude
+2. Claude analyzes the available tools and decides which one(s) to use
+3. The client executes the chosen tool(s) through the MCP server
+4. The results are sent back to Claude
+5. Claude formulates a natural language response
+6. The response is displayed to you!
## Troubleshooting
-
- 1. Check if MCP is enabled:
- - Click the π icon in Claude Desktop, next to the chat box
- - Expand "Installed MCP Servers"
- - You should see your configured servers
+
+**Error: Failed to retrieve grid point data**
- 2. Verify your config:
- - From Claude Desktop, go to Claude > Settingsβ¦
- - Open the "Developer" tab to see your configuration
+This usually means either:
+1. The coordinates are outside the US
+2. The NWS API is having issues
+3. You're being rate limited
- 3. Restart Claude Desktop completely:
- - Quit the app (not just close the window)
- - Start it again
-
+Fix:
-
- 1. Check Claude Desktop's logs:
- ```bash
- tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
- ```
+- Verify you're using US coordinates
+- Add a small delay between requests
+- Check the NWS API status page
- 2. Verify database access:
- ```bash
- # Test database connection
- sqlite3 ~/test.db ".tables"
- ```
+**Error: No active alerts for [STATE]**
- 3. Common fixes:
- - Check file paths in your config
- - Verify database file permissions
- - Ensure SQLite is installed properly
-
+This isn't an error - it just means there are no current weather alerts for that state. Try a different state or check during severe weather.
+
+
+**Server not showing up in Claude**
+1. Check your configuration file syntax
+2. Make sure the path to your project is correct
+3. Restart Claude for Desktop completely
+
+You can also check Claude's logs for errors like so:
+```bash
+# Check Claude's logs for errors
+tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
+```
+
+**Tool calls failing silently**
+
+If Claude attempts to use the tools but they fail:
+
+1. Check Claude's logs for errors
+2. Verify your server runs without errors
+3. Try restarting Claude for Desktop
+
## Next steps
-
-
- Create your own MCP servers to give your LLM clients new capabilities.
+
+
+ Learn how to build your an MCP client that can connect to your server
-
-
- Browse our collection of example servers to see what's possible.
+
+ Check out our gallery of official MCP servers and implementations
-
+
+ Understand how MCP connects clients, servers, and LLMs
+
+
\ No newline at end of file
diff --git a/tutorials/building-a-client-node.mdx b/tutorials/building-a-client-node.mdx
new file mode 100644
index 0000000..9cc5ccc
--- /dev/null
+++ b/tutorials/building-a-client-node.mdx
@@ -0,0 +1,463 @@
+
+## System Requirements
+
+Before starting, ensure your system meets these requirements:
+- Mac or Windows computer
+- Node.js version 16 or higher installed
+- npm (comes with Node.js)
+
+## Setting Up Your Environment
+
+First, create a new Node.js project:
+
+```bash
+# Create project directory
+mkdir mcp-client
+cd mcp-client
+
+# Initialize npm project
+npm init -y
+
+# Install dependencies
+npm install @modelcontextprotocol/sdk @anthropic-ai/sdk dotenv
+npm install -D typescript @types/node
+
+# Create TypeScript config
+npx tsc --init
+
+# Create necessary files
+mkdir src
+touch src/client.ts
+touch .env
+```
+
+Update your `package.json` to add necessary configuration:
+
+```json
+{
+ "type": "module",
+ "scripts": {
+ "build": "tsc",
+ "start": "node build/client.js"
+ }
+}
+```
+
+Update your `tsconfig.json` with appropriate settings:
+
+```json
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "Node16",
+ "moduleResolution": "Node16",
+ "outDir": "./build",
+ "rootDir": "./src",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true
+ },
+ "include": ["src/**/*"]
+}
+```
+
+## Setting Up Your API Key
+
+You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
+
+Create a `.env` file:
+```bash
+ANTHROPIC_API_KEY=your_key_here
+```
+
+Add `.env` to your `.gitignore`:
+```bash
+echo ".env" >> .gitignore
+```
+
+## Creating the Client
+
+First, let's set up our imports and create the basic client class in `src/client.ts`:
+
+```typescript
+import { Client } from "@modelcontextprotocol/sdk/client/index.js";
+import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
+import Anthropic from "@anthropic-ai/sdk";
+import dotenv from "dotenv";
+import { Tool } from "@anthropic-ai/sdk/resources/messages.js";
+import {
+ CallToolResultSchema,
+ ListToolsResultSchema,
+} from "@modelcontextprotocol/sdk/types.js";
+import * as readline from "node:readline";
+
+dotenv.config();
+
+interface MCPClientConfig {
+ name?: string;
+ version?: string;
+}
+
+class MCPClient {
+ private client: Client | null = null;
+ private anthropic: Anthropic;
+ private transport: StdioClientTransport | null = null;
+
+ constructor(config: MCPClientConfig = {}) {
+ this.anthropic = new Anthropic();
+ }
+
+ // Methods will go here
+}
+```
+
+## Server Connection Management
+
+Next, implement the method to connect to an MCP server:
+
+```typescript
+ async connectToServer(serverScriptPath: string): Promise {
+ const isPython = serverScriptPath.endsWith(".py");
+ const isJs = serverScriptPath.endsWith(".js");
+
+ if (!isPython && !isJs) {
+ throw new Error("Server script must be a .py or .js file");
+ }
+
+ const command = isPython ? "python" : "node";
+
+ this.transport = new StdioClientTransport({
+ command,
+ args: [serverScriptPath],
+ });
+
+ this.client = new Client(
+ {
+ name: "mcp-client",
+ version: "1.0.0",
+ },
+ {
+ capabilities: {},
+ }
+ );
+
+ await this.client.connect(this.transport);
+
+ // List available tools
+ const response = await this.client.request(
+ { method: "tools/list" },
+ ListToolsResultSchema
+ );
+
+ console.log(
+ "\nConnected to server with tools:",
+ response.tools.map((tool: any) => tool.name)
+ );
+ }
+```
+
+## Query Processing Logic
+
+Now add the core functionality for processing queries and handling tool calls:
+
+```typescript
+ async processQuery(query: string): Promise {
+ if (!this.client) {
+ throw new Error("Client not connected");
+ }
+
+ // Initialize messages array with user query
+ let messages: Anthropic.MessageParam[] = [
+ {
+ role: "user",
+ content: query,
+ },
+ ];
+
+ // Get available tools
+ const toolsResponse = await this.client.request(
+ { method: "tools/list" },
+ ListToolsResultSchema
+ );
+
+ const availableTools: Tool[] = toolsResponse.tools.map((tool: any) => ({
+ name: tool.name,
+ description: tool.description,
+ input_schema: tool.inputSchema,
+ }));
+
+ const finalText: string[] = [];
+ let currentResponse = await this.anthropic.messages.create({
+ model: "claude-3-5-sonnet-20241022",
+ max_tokens: 1000,
+ messages,
+ tools: availableTools,
+ });
+
+ // Process the response and any tool calls
+ while (true) {
+ // Add Claude's response to final text and messages
+ for (const content of currentResponse.content) {
+ if (content.type === "text") {
+ finalText.push(content.text);
+ } else if (content.type === "tool_use") {
+ const toolName = content.name;
+ const toolArgs = content.input;
+
+ // Execute tool call
+ const result = await this.client.request(
+ {
+ method: "tools/call",
+ params: {
+ name: toolName,
+ args: toolArgs,
+ },
+ },
+ CallToolResultSchema
+ );
+
+ finalText.push(
+ `[Calling tool ${toolName} with args ${JSON.stringify(toolArgs)}]`
+ );
+
+ // Add Claude's response (including tool use) to messages
+ messages.push({
+ role: "assistant",
+ content: currentResponse.content,
+ });
+
+ // Add tool result to messages
+ messages.push({
+ role: "user",
+ content: [
+ {
+ type: "tool_result",
+ tool_use_id: content.id,
+ content: [
+ { type: "text", text: JSON.stringify(result.content) },
+ ],
+ },
+ ],
+ });
+
+ // Get next response from Claude with tool results
+ currentResponse = await this.anthropic.messages.create({
+ model: "claude-3-5-sonnet-20241022",
+ max_tokens: 1000,
+ messages,
+ tools: availableTools,
+ });
+
+ // Add Claude's interpretation of the tool results to final text
+ if (currentResponse.content[0]?.type === "text") {
+ finalText.push(currentResponse.content[0].text);
+ }
+
+ // Continue the loop to process any additional tool calls
+ continue;
+ }
+ }
+
+ // If we reach here, there were no tool calls in the response
+ break;
+ }
+
+ return finalText.join("\n");
+ }
+
+```
+
+## Interactive Chat Interface
+
+Add the chat loop and cleanup functionality:
+
+```typescript
+ async chatLoop(): Promise {
+ console.log("\nMCP Client Started!");
+ console.log("Type your queries or 'quit' to exit.");
+
+ // Using Node's readline for console input
+ const rl = readline.createInterface({
+ input: process.stdin,
+ output: process.stdout,
+ });
+
+ const askQuestion = () => {
+ rl.question("\nQuery: ", async (query: string) => {
+ try {
+ if (query.toLowerCase() === "quit") {
+ await this.cleanup();
+ rl.close();
+ return;
+ }
+
+ const response = await this.processQuery(query);
+ console.log("\n" + response);
+ askQuestion();
+ } catch (error) {
+ console.error("\nError:", error);
+ askQuestion();
+ }
+ });
+ };
+
+ askQuestion();
+ }
+
+ async cleanup(): Promise {
+ if (this.transport) {
+ await this.transport.close();
+ }
+ }
+```
+
+## Main Entry Point
+
+Finally, add the main execution logic outside the class:
+
+```typescript
+// Main execution
+async function main() {
+ if (process.argv.length < 3) {
+ console.log("Usage: ts-node client.ts ");
+ process.exit(1);
+ }
+
+ const client = new MCPClient();
+ try {
+ await client.connectToServer(process.argv[2]);
+ await client.chatLoop();
+ } catch (error) {
+ console.error("Error:", error);
+ await client.cleanup();
+ process.exit(1);
+ }
+}
+
+// Run main if this is the main module
+if (import.meta.url === new URL(process.argv[1], "file:").href) {
+ main();
+}
+
+export default MCPClient;
+```
+
+## Running the Client
+
+To run your client with any MCP server:
+
+```bash
+# Build the TypeScript code. Make sure to rerun this every time you update `client.ts`!
+npm run build
+
+# Run the client
+node build/client.js path/to/server.py # for Python servers
+node build/client.js path/to/server.js # for Node.js servers
+```
+
+The client will:
+1. Connect to the specified server
+2. List available tools
+3. Start an interactive chat session where you can:
+ - Enter queries
+ - See tool executions
+ - Get responses from Claude
+
+## Key Components Explained
+
+#### 1. Client Initialization
+- The `MCPClient` class initializes with session management and API clients
+- Sets up the MCP client with basic capabilities
+- Configures the Anthropic client for Claude interactions
+
+#### 2. Server Connection
+- Supports both Python and Node.js servers
+- Validates server script type
+- Sets up proper communication channels
+- Lists available tools on connection
+
+#### 3. Query Processing
+- Maintains conversation context
+- Handles Claude's responses and tool calls
+- Manages the message flow between Claude and tools
+- Combines results into a coherent response
+
+#### 4. Interactive Interface
+- Provides a simple command-line interface
+- Handles user input and displays responses
+- Includes basic error handling
+- Allows graceful exit
+
+#### 5. Resource Management
+- Proper cleanup of resources
+- Error handling for connection issues
+- Graceful shutdown procedures
+
+### Common Customization Points
+
+1. **Tool Handling**
+ - Modify `processQuery()` to handle specific tool types
+ - Add custom error handling for tool calls
+ - Implement tool-specific response formatting
+
+2. **Response Processing**
+ - Customize how tool results are formatted
+ - Add response filtering or transformation
+ - Implement custom logging
+
+3. **User Interface**
+ - Add a GUI or web interface
+ - Implement rich console output
+ - Add command history or auto-completion
+
+### Best Practices
+
+1. **Error Handling**
+ - Always wrap tool calls in try-catch blocks
+ - Provide meaningful error messages
+ - Gracefully handle connection issues
+
+2. **Resource Management**
+ - Use proper cleanup methods
+ - Close connections when done
+ - Handle server disconnections
+
+3. **Security**
+ - Store API keys securely in `.env`
+ - Validate server responses
+ - Be cautious with tool permissions
+
+### Troubleshooting
+
+#### Server Path Issues
+- Double-check the path to your server script
+- Use absolute paths if relative paths aren't working
+- For Windows users, use forward slashes (/) or escaped backslashes (\\)
+- Verify the server file has the correct extension (.py or .js)
+
+Example of correct path usage:
+```bash
+# Relative path
+node build/client.js ./server/weather.js
+
+# Absolute path
+node build/client.js /Users/username/projects/mcp-server/weather.js
+
+# Windows path (either format works)
+node build/client.js C:/projects/mcp-server/weather.js
+node build/client.js C:\\projects\\mcp-server\\weather.js
+```
+
+#### Connection Issues
+- Verify the server script exists and has correct permissions
+- Check that the server script is executable
+- Ensure the server script's dependencies are installed
+- Try running the server script directly to check for errors
+
+#### Tool Execution Issues
+- Check server logs for error messages
+- Verify tool input arguments match the schema
+- Ensure tool dependencies are available
+- Add debug logging to track execution flow
+
\ No newline at end of file
diff --git a/tutorials/building-a-client.mdx b/tutorials/building-a-client.mdx
new file mode 100644
index 0000000..d432f38
--- /dev/null
+++ b/tutorials/building-a-client.mdx
@@ -0,0 +1,414 @@
+---
+title: "Building MCP clients"
+description: "Learn how to build your first client in MCP"
+---
+
+In this tutorial, you'll learn how to build a client application that connects to MCP servers. It helps to have gone through the [Quickstart tutorial](/quickstart) that guides you through the basic of building your first server.
+
+
+
+
+## System Requirements
+
+Before starting, ensure your system meets these requirements:
+- Mac or Windows computer
+- Latest Python version installed
+- Latest version of `uv` installed
+
+## Setting Up Your Environment
+
+First, create a new Python project with `uv`:
+
+```bash
+# Create project directory
+uv init mcp-client
+cd mcp-client
+
+# Create virtual environment
+uv venv
+
+# Activate virtual environment
+# On Windows:
+.venv\Scripts\activate
+# On Unix or MacOS:
+source .venv/bin/activate
+
+# Install required packages
+uv add mcp anthropic python-dotenv
+
+# Remove boilerplate files
+rm hello.py
+
+# Create our main file
+touch client.py
+```
+
+## Setting Up Your API Key
+
+You'll need an Anthropic API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).
+
+Create a `.env` file to store it:
+
+```bash
+# Create .env file
+touch .env
+```
+
+Add your key to the `.env` file:
+```bash
+ANTHROPIC_API_KEY=
+```
+
+Add `.env` to your `.gitignore`:
+```bash
+echo ".env" >> .gitignore
+```
+
+
+Make sure you keep your `ANTHROPIC_API_KEY` secure!
+
+
+## Creating the Client
+
+### Basic Client Structure
+First, let's set up our imports and create the basic client class:
+
+```python
+import asyncio
+from typing import Optional
+from contextlib import AsyncExitStack
+
+from mcp import ClientSession, StdioServerParameters
+from mcp.client.stdio import stdio_client
+
+from anthropic import Anthropic
+from dotenv import load_dotenv
+
+load_dotenv() # load environment variables from .env
+
+class MCPClient:
+ def __init__(self):
+ # Initialize session and client objects
+ self.session: Optional[ClientSession] = None
+ self.exit_stack = AsyncExitStack()
+ self.anthropic = Anthropic()
+ # methods will go here
+```
+
+### Server Connection Management
+
+Next, we'll implement the method to connect to an MCP server:
+
+```python
+async def connect_to_server(self, server_script_path: str):
+ """Connect to an MCP server
+
+ Args:
+ server_script_path: Path to the server script (.py or .js)
+ """
+ is_python = server_script_path.endswith('.py')
+ is_js = server_script_path.endswith('.js')
+ if not (is_python or is_js):
+ raise ValueError("Server script must be a .py or .js file")
+
+ command = "python" if is_python else "node"
+ server_params = StdioServerParameters(
+ command=command,
+ args=[server_script_path],
+ env=None
+ )
+
+ stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))
+ self.stdio, self.write = stdio_transport
+ self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.write))
+
+ await self.session.initialize()
+
+ # List available tools
+ response = await self.session.list_tools()
+ tools = response.tools
+ print("\nConnected to server with tools:", [tool.name for tool in tools])
+```
+
+### Query Processing Logic
+
+Now let's add the core functionality for processing queries and handling tool calls:
+
+```python
+async def process_query(self, query: str) -> str:
+ """Process a query using Claude and available tools"""
+ messages = [
+ {
+ "role": "user",
+ "content": query
+ }
+ ]
+
+ response = await self.session.list_tools()
+ available_tools = [{
+ "name": tool.name,
+ "description": tool.description,
+ "input_schema": tool.inputSchema
+ } for tool in response.tools]
+
+ # Initial Claude API call
+ response = self.anthropic.messages.create(
+ model="claude-3-5-sonnet-20241022",
+ max_tokens=1000,
+ messages=messages,
+ tools=available_tools
+ )
+
+ # Process response and handle tool calls
+ tool_results = []
+ final_text = []
+
+ for content in response.content:
+ if content.type == 'text':
+ final_text.append(content.text)
+ elif content.type == 'tool_use':
+ tool_name = content.name
+ tool_args = content.input
+
+ # Execute tool call
+ result = await self.session.call_tool(tool_name, tool_args)
+ tool_results.append({"call": tool_name, "result": result})
+ final_text.append(f"[Calling tool {tool_name} with args {tool_args}]")
+
+ # Continue conversation with tool results
+ if hasattr(content, 'text') and content.text:
+ messages.append({
+ "role": "assistant",
+ "content": content.text
+ })
+ messages.append({
+ "role": "user",
+ "content": result.content
+ })
+
+ # Get next response from Claude
+ response = self.anthropic.messages.create(
+ model="claude-3-5-sonnet-20241022",
+ max_tokens=1000,
+ messages=messages,
+ )
+
+ final_text.append(response.content[0].text)
+
+ return "\n".join(final_text)
+```
+
+### Interactive Chat Interface
+Now we'll add the chat loop and cleanup functionality:
+
+```python
+async def chat_loop(self):
+ """Run an interactive chat loop"""
+ print("\nMCP Client Started!")
+ print("Type your queries or 'quit' to exit.")
+
+ while True:
+ try:
+ query = input("\nQuery: ").strip()
+
+ if query.lower() == 'quit':
+ break
+
+ response = await self.process_query(query)
+ print("\n" + response)
+
+ except Exception as e:
+ print(f"\nError: {str(e)}")
+
+async def cleanup(self):
+ """Clean up resources"""
+ await self.exit_stack.aclose()
+```
+
+### Main Entry Point
+
+Finally, we'll add the main execution logic:
+
+```python
+async def main():
+ if len(sys.argv) < 2:
+ print("Usage: python client.py ")
+ sys.exit(1)
+
+ client = MCPClient()
+ try:
+ await client.connect_to_server(sys.argv[1])
+ await client.chat_loop()
+ finally:
+ await client.cleanup()
+
+if __name__ == "__main__":
+ import sys
+ asyncio.run(main())
+```
+
+You can find the complete `client.py` file [here.](https://gist.github.com/zckly/f3f28ea731e096e53b39b47bf0a2d4b1)
+
+## Key Components Explained
+
+### 1. Client Initialization
+- The `MCPClient` class initializes with session management and API clients
+- Uses `AsyncExitStack` for proper resource management
+- Configures the Anthropic client for Claude interactions
+
+### 2. Server Connection
+- Supports both Python and Node.js servers
+- Validates server script type
+- Sets up proper communication channels
+- Initializes the session and lists available tools
+
+### 3. Query Processing
+- Maintains conversation context
+- Handles Claude's responses and tool calls
+- Manages the message flow between Claude and tools
+- Combines results into a coherent response
+
+### 4. Interactive Interface
+- Provides a simple command-line interface
+- Handles user input and displays responses
+- Includes basic error handling
+- Allows graceful exit
+
+### 5. Resource Management
+- Proper cleanup of resources
+- Error handling for connection issues
+- Graceful shutdown procedures
+
+## Common Customization Points
+
+1. **Tool Handling**
+ - Modify `process_query()` to handle specific tool types
+ - Add custom error handling for tool calls
+ - Implement tool-specific response formatting
+
+2. **Response Processing**
+ - Customize how tool results are formatted
+ - Add response filtering or transformation
+ - Implement custom logging
+
+3. **User Interface**
+ - Add a GUI or web interface
+ - Implement rich console output
+ - Add command history or auto-completion
+
+## Running the Client
+
+To run your client with any MCP server:
+
+```bash
+uv run client.py path/to/server.py # python server
+uv run client.py path/to/build/index.js # node server
+```
+
+
+If you're continuing the weather tutorial from the quickstart, your command might look something like this: `python client.py .../weather/src/weather/server.py`
+
+
+The client will:
+1. Connect to the specified server
+2. List available tools
+3. Start an interactive chat session where you can:
+ - Enter queries
+ - See tool executions
+ - Get responses from Claude
+
+Here's an example of what it should look like if connected to the weather server from the quickstart:
+
+
+
+
+
+## How It Works
+
+When you submit a query:
+
+1. The client gets the list of available tools from the server
+2. Your query is sent to Claude along with tool descriptions
+3. Claude decides which tools (if any) to use
+4. The client executes any requested tool calls through the server
+5. Results are sent back to Claude
+6. Claude provides a natural language response
+7. The response is displayed to you
+
+## Best practices
+
+1. **Error Handling**
+ - Always wrap tool calls in try-catch blocks
+ - Provide meaningful error messages
+ - Gracefully handle connection issues
+
+2. **Resource Management**
+ - Use `AsyncExitStack` for proper cleanup
+ - Close connections when done
+ - Handle server disconnections
+
+3. **Security**
+ - Store API keys securely in `.env`
+ - Validate server responses
+ - Be cautious with tool permissions
+
+## Troubleshooting
+
+### Server Path Issues
+- Double-check the path to your server script is correct
+- Use the absolute path if the relative path isn't working
+- For Windows users, make sure to use forward slashes (/) or escaped backslashes (\\) in the path
+- Verify the server file has the correct extension (.py for Python or .js for Node.js)
+
+Example of correct path usage:
+```bash
+# Relative path
+uv run client.py ./server/weather.py
+
+# Absolute path
+uv run client.py /Users/username/projects/mcp-server/weather.py
+
+# Windows path (either format works)
+uv run client.py C:/projects/mcp-server/weather.py
+uv run client.py C:\\projects\\mcp-server\\weather.py
+```
+
+### Response Timing
+- The first response might take up to 30 seconds to return
+- This is normal and happens while:
+ - The server initializes
+ - Claude processes the query
+ - Tools are being executed
+- Subsequent responses are typically faster
+- Don't interrupt the process during this initial waiting period
+
+### Common Error Messages
+
+If you see:
+- `FileNotFoundError`: Check your server path
+- `Connection refused`: Ensure the server is running and the path is correct
+- `Tool execution failed`: Verify the tool's required environment variables are set
+- `Timeout error`: Consider increasing the timeout in your client configuration
+
+
+
+
+
+## Next steps
+
+
+
+ Check out our gallery of official MCP servers and implementations
+
+
+ Understand how MCP connects clients, servers, and LLMs
+
+
\ No newline at end of file
diff --git a/tutorials/building-mcp-with-claude.mdx b/tutorials/building-mcp-with-claude.mdx
new file mode 100644
index 0000000..d080553
--- /dev/null
+++ b/tutorials/building-mcp-with-claude.mdx
@@ -0,0 +1,73 @@
+---
+title: "Building MCP with Claude"
+description: "Speed up your MCP development with Claude!"
+---
+
+This guide will help you use Claude to build custom Model Context Protocol (MCP) servers and clients.
+
+## Preparing the documentation
+
+Before starting, gather the necessary documentation to help Claude understand MCP:
+
+1. Visit https://modelcontextprotocol.io/llms-full.txt and copy the full documentation text
+2. Navigate to either the [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk) or [Python SDK repository](https://github.com/modelcontextprotocol/python-sdk)
+3. Copy the README files and other relevant documentation
+4. Paste these documents into your conversation with Claude
+
+## Describing your server
+
+Once you've provided the documentation, clearly describe to Claude what kind of server you want to build. Be specific about:
+
+- What resources your server will expose
+- What tools it will provide
+- Any prompts it should offer
+- What external systems it needs to interact with
+
+For example:
+```
+Build an MCP server that:
+- Connects to my company's PostgreSQL database
+- Exposes table schemas as resources
+- Provides tools for running read-only SQL queries
+- Includes prompts for common data analysis tasks
+```
+
+## Working with Claude
+
+When working with Claude on MCP servers:
+
+1. Start with the core functionality first, then iterate to add more features
+2. Ask Claude to explain any parts of the code you don't understand
+3. Request modifications or improvements as needed
+4. Have Claude help you test the server and handle edge cases
+
+Claude can help implement all the key MCP features:
+
+- Resource management and exposure
+- Tool definitions and implementations
+- Prompt templates and handlers
+- Error handling and logging
+- Connection and transport setup
+
+## Best practices
+
+When building MCP servers with Claude:
+
+- Break down complex servers into smaller pieces
+- Test each component thoroughly before moving on
+- Keep security in mind - validate inputs and limit access appropriately
+- Document your code well for future maintenance
+- Follow MCP protocol specifications carefully
+
+## Next steps
+
+After Claude helps you build your server:
+
+1. Review the generated code carefully
+2. Test the server with the MCP Inspector tool
+3. Connect it to Claude.app or other MCP clients
+4. Iterate based on real usage and feedback
+
+Remember that Claude can help you modify and improve your server as requirements change over time.
+
+Need more guidance? Just ask Claude specific questions about implementing MCP features or troubleshooting issues that arise.
\ No newline at end of file