### Install and Run Sampling Example
Source: https://docs.mcp-use.com/typescript/server/sampling
Commands to install dependencies and run the server-side sampling example locally. The server will be available at http://localhost:3000.
```bash
cd libraries/typescript/packages/mcp-use/examples/server/sampling
pnpm install
pnpm dev
```
--------------------------------
### Quick Start Agent Example
Source: https://docs.mcp-use.com/typescript/agent/index
A basic example demonstrating how to create and run an MCPAgent. Ensure you have the necessary LLM and MCP server configurations.
```typescript
import { MCPAgent, MCPClient } from "mcp-use";
import { ChatOpenAI } from "@langchain/openai";
const client = new MCPClient({
mcpServers: {
filesystem: {
command: "npx",
args: ["-y", "@modelcontextprotocol/server-filesystem", "./"],
},
},
});
const llm = new ChatOpenAI({ model: "gpt-5.5" });
const agent = new MCPAgent({ llm, client, maxSteps: 50 });
agent.run({
prompt: "What is in the current folder?"
}).then(async (response) => {
console.log(response);
await agent.close();
});
```
--------------------------------
### Install and Deploy MCP Server CLI
Source: https://docs.mcp-use.com/typescript/server/deployment/mcp-use
Install the mcp-use CLI, log in to Manufact Cloud, and deploy your MCP server. This is the quickest way to get a production-ready URL.
```bash
# Install the CLI (if you are using create-mcp-use-app this step is not needed)
npm install -g @mcp-use/cli
# Login to Manufact Cloud
npm run mcp-use login
# Deploy your server
npm run mcp-use deploy
```
--------------------------------
### Complete Server Manager Example
Source: https://docs.mcp-use.com/python/agent/server-manager
Demonstrates a full agent setup with a multi-server configuration and a complex task involving various tools. Use this to see the Server Manager in action with multiple MCP servers.
```Python
import asyncio
from mcp_use import MCPClient, MCPAgent
from langchain_openai import ChatOpenAI
async def demo_server_manager():
# Multi-server configuration
client = MCPClient.from_dict({
"mcpServers": {
"web": {"command": "npx", "args": ["@playwright/mcp@latest"]},
"files": {"command": "uvx", "args": ["mcp-server-filesystem", "/tmp"]},
"database": {"command": "uvx", "args": ["mcp-server-sqlite"]}
}
})
# Agent with Server Manager
agent = MCPAgent(
llm=ChatOpenAI(model="gpt-4"),
client=client,
use_server_manager=True,
verbose=True # See the magic happen!
)
# Complex multi-server task
result = await agent.run("""
I need to build a complete data collection system:
1. First, show me what servers and tools are available
2. Scrape product information from https://example-store.com
3. Clean and structure the data
4. Save it as both JSON and CSV files
5. Load the data into a SQLite database
6. Generate a summary report
Guide me through each step and show me how you discover and use the right tools.
""")
print("Task completed!")
print(result)
await agent.close()
if __name__ == "__main__":
asyncio.run(demo_server_manager())
```
--------------------------------
### Complete File Manager Server Example with Client Roots
Source: https://docs.mcp-use.com/python/client/roots
Demonstrates a full client setup exposing workspace and configuration directories to a file management server. Includes client initialization, session creation, and calling a server tool. Ensure asyncio and necessary MCP types are imported.
```Python
import asyncio
from mcp.types import Root
from mcp_use.client import MCPClient
async def main():
# Expose workspace directories to the server
roots = [
Root(uri="file:///home/user/workspace", name="Workspace"),
Root(uri="file:///home/user/config", name="Config Files"),
]
config = {
"mcpServers": {
"file-manager": {"url": "http://localhost:8000/mcp"}
}
}
client = MCPClient(config, roots=roots)
try:
await client.create_all_sessions()
session = client.get_session("file-manager")
# The server can now query available roots
# and operate on files within them
result = await session.call_tool("list_files", {})
print(result.content[0].text)
finally:
await client.close_all_sessions()
if __name__ == "__main__":
asyncio.run(main())
```
--------------------------------
### Run Streaming Tool Props Example
Source: https://docs.mcp-use.com/typescript/server/examples
Execute the streaming tool props example from the mcp-use package root. This command starts a server demonstrating how to stream tool arguments to widgets for live previews.
```bash
pnpm run example:server:streaming-props
```
--------------------------------
### Run Completion Example
Source: https://docs.mcp-use.com/typescript/client/completion
Execute the provided bash command to run a full Node.js example demonstrating prompt and resource template completions. This command starts both the completion server and the client.
```bash
# From packages/mcp-use:
pnpm run example:completion
```
--------------------------------
### Build and Start MCP Server Locally
Source: https://docs.mcp-use.com/typescript/server/deployment/mcp-use
Commands to build your MCP server and start it locally for testing before deployment. Ensure you have the mcp-use CLI installed.
```bash
# Build and test locally
mcp-use build
mcp-use start
```
--------------------------------
### Quick Start: Bearer Token Authentication Setup
Source: https://docs.mcp-use.com/python/server/auth/bearer
Implement a custom BearerAuthProvider to verify tokens and integrate it with your MCPServer. This example shows how to define API keys and access user claims within a tool.
```python
from mcp_use.server import MCPServer
from mcp_use.server.auth import BearerAuthProvider, AccessToken, get_access_token
API_KEYS = {
"sk-abc123": {"email": "alice@example.com"},
"sk-def456": {"email": "bob@example.com"},
}
class MyAuthProvider(BearerAuthProvider):
async def verify_token(self, token: str) -> AccessToken | None:
if token not in API_KEYS:
return None
return AccessToken(token=token, claims=API_KEYS[token])
server = MCPServer(name="my-server", auth=MyAuthProvider())
@server.tool()
def whoami() -> str:
"""Get current user info."""
token = get_access_token()
return f"Hello {token.claims.get('email')}" if token else "Not authenticated"
```
--------------------------------
### Install mcp-use
Source: https://docs.mcp-use.com/home/redirects/python
Install the mcp-use package for using the MCP Client.
```bash
pip install mcp-use
```
--------------------------------
### Google MCP Adapter Integration Example
Source: https://docs.mcp-use.com/python/integration/google
This example shows the full integration flow using the GoogleMCPAdapter. It covers client initialization, adapter creation, tool conversion, and multi-turn tool execution with Google's Gemini SDK. Ensure you have the necessary libraries installed and environment variables configured.
```python
from dotenv import load_dotenv
import asyncio
from mcp import MCPClient, types
from mcp.adapters.google import GoogleMCPAdapter
import google.generativeai as genai
load_dotenv()
async def main():
config = {
"mcpServers": {"playwright": {"command": "npx", "args": ["@playwright/mcp@latest"], "env": {"DISPLAY": ":1"}}}
}
try:
client = MCPClient(config=config)
# Creates the adapter for Google's format
adapter = GoogleMCPAdapter()
# Convert tools from active connectors to Google's format
await adapter.create_all(client)
# List concatenation (if you loaded all tools)
all_tools = adapter.tools + adapter.resources + adapter.prompts
google_tools = [types.Tool(function_declarations=all_tools)]
# If you don't want to create all tools, you can call single functions
# await adapter.create_tools(client)
# await adapter.create_resources(client)
# await adapter.create_prompts(client)
# Use tools with Google's SDK (not agent in this case)
gemini = genai.Client()
messages = [
types.Content(
role="user",
parts=[
types.Part.from_text(
text="Please search on the internet using browser: 'What time is it in Favignana now!'"
)
],
)
]
# Initial request
response = gemini.models.generate_content(
model="gemini-flash-lite-latest", contents=messages, config=types.GenerateContentConfig(tools=google_tools)
)
if not response.function_calls:
print("The model didn't do any tool call!")
return
# Do multiple tool calls if needed
while response.function_calls:
for function_call in response.function_calls:
function_call_content = response.candidates[0].content
messages.append(function_call_content)
tool_name = function_call.name
arguments = function_call.args
# Use the adapter's map to get the correct executor
executor = adapter.tool_executors.get(tool_name)
if not executor:
print(f"Error: Unknown tool '{tool_name}' requested by model.")
function_response_content = types.Content(
role="tool",
parts=[
types.Part.from_function_response(
name=tool_name,
response={"error": "No executor found for the tool requested"},
)
],
)
else:
try:
# Execute the tool using the retrieved function
print(f"Executing tool: {tool_name}({arguments})")
tool_result = await executor(**arguments)
# Use the adapter's universal parser
content = adapter.parse_result(tool_result)
function_response = {"result": content}
# Build function response message
function_response_part = types.Part.from_function_response(
name=tool_name,
response=function_response,
)
function_response_content = types.Content(role="tool", parts=[function_response_part])
except Exception as e:
print(f"An unexpected error occurred while executing tool {tool_name}: {e}")
function_response_content = types.Content(
role="tool",
parts=[
types.Part.from_function_response(
name=tool_name,
response={"error": str(e)},
)
],
)
# Append the tool's result to the conversation history
messages.append(function_response_content)
# Send the tool's result back to the model to get the next response
response = gemini.models.generate_content(
model="gemini-flash-lite-latest",
contents=messages,
config=types.GenerateContentConfig(tools=google_tools),
)
# Get final response, the loop has finished
print("\n--- Final response from the model ---")
if response.text:
print(response.text)
else:
print("The model did not return a final text response.")
print(response)
gemini.close()
except Exception as e:
print(f"Error: {e}")
raise e
if __name__ == "__main__":
asyncio.run(main())
```
--------------------------------
### Python Agent Example
Source: https://docs.mcp-use.com/home
Instantiates an MCP Agent and runs a command to list files. Requires MCPClient and MCPAgent setup.
```python
client = MCPClient.from_dict({ "mcpServers": { "fs": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"] } } })
agent = MCPAgent(llm=ChatOpenAI(model="gpt-5.5"), client=client)
result = await agent.run("List all files in the directory")
```
--------------------------------
### Basic MCPAgent Configuration
Source: https://docs.mcp-use.com/python/agent/agent-configuration
Illustrates the basic setup for creating an MCPAgent instance with essential parameters like the language model and client configuration. This is a starting point for agent initialization.
```python
from mcp_use import MCPAgent, MCPClient
from langchain_openai import ChatOpenAI
# Basic configuration
agent = MCPAgent(
llm=ChatOpenAI(model="gpt-5.5", temperature=0.7),
client=MCPClient.from_config_file("config.json"),
max_steps=30
)
```
--------------------------------
### Complete LangChain Integration Example
Source: https://docs.mcp-use.com/python/integration/langchain
A complete, runnable Python script demonstrating the integration of mcp-use with LangChain, including all necessary imports and setup.
```python
import asyncio
from dataclasses import dataclass
from dotenv import load_dotenv
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from mcp_use import MCPClient
from mcp_use.agents.adapters import LangChainAdapter
```
--------------------------------
### Combined Server Configuration Example
Source: https://docs.mcp-use.com/python/server/logging
Configure an MCPServer with various settings including debug mode, log filtering, and pretty-printed JSON-RPC. This snippet shows how to initialize the server and start it with a specific transport.
```python
server = MCPServer(
name="my-server",
debug=True,
show_inspector_logs=False, # Hide inspector noise
mcp_logs_only=True, # Only show MCP protocol logs
pretty_print_jsonrpc=True, # Pretty-printed JSON-RPC panels
)
server.run(transport="streamable-http")
```
--------------------------------
### Start Docker on Windows
Source: https://docs.mcp-use.com/typescript/server/deployment/supabase
Instructions to start Docker Desktop on Windows and verify it's running.
```bash
# Open Docker Desktop from Start Menu or run:
# "C:\Program Files\Docker\Docker\Docker Desktop.exe"
# Verify Docker is running (in PowerShell):
docker info
```
--------------------------------
### Create a New MCP Server Project
Source: https://docs.mcp-use.com/typescript/getting-started/quickstart
Scaffold a new MCP server project using the create-mcp-use-app command, install dependencies, and start the development server.
```bash
npx create-mcp-use-app my-mcp-server
cd my-mcp-server
npm install
npm run dev
```
--------------------------------
### Install mcp-use CLI
Source: https://docs.mcp-use.com/typescript/client/cli
Install the mcp-use CLI globally using npm or npx.
```bash
npm install -g mcp-use
# or
npx mcp-use client --help
```
--------------------------------
### Start Docker on Linux
Source: https://docs.mcp-use.com/typescript/server/deployment/supabase
Instructions to start the Docker service on Linux and verify it's running.
```bash
# Start Docker service:
sudo systemctl start docker
# Verify Docker is running:
docker info
```
--------------------------------
### install_dependencies
Source: https://docs.mcp-use.com/python/api-reference/mcp_use_server_templates_cli
Prompts the user to install dependencies for the project in the specified target directory and runs the installer. Returns True if dependencies were installed.
```APIDOC
## install_dependencies
### Description
Prompts user to install dependencies and run the installer. Returns True if installed.
### Parameters
#### Path Parameters
- **target_dir** (pathlib.Path) - Required - The target directory for which to install dependencies.
### Returns
- **returns** (bool) - True if dependencies were installed, False otherwise.
### Signature
```python
def install_dependencies(target_dir: pathlib.Path):
```
```
--------------------------------
### Install LangChain SDK
Source: https://docs.mcp-use.com/python/integration/langchain
Install the LangChain SDK using pip. This is a prerequisite for using the adapter.
```bash
uv pip install langchain
```
--------------------------------
### Install mcp-use Package
Source: https://docs.mcp-use.com/typescript/agent/index
Install the mcp-use package using npm, pnpm, or yarn.
```bash
npm install mcp-use
```
```bash
pnpm add mcp-use
```
```bash
yarn add mcp-use
```
--------------------------------
### Start Docker on macOS
Source: https://docs.mcp-use.com/typescript/server/deployment/supabase
Instructions to start Docker Desktop on macOS and verify it's running.
```bash
# If you have Docker Desktop installed:
open -a Docker
# Verify Docker is running:
docker info
```
--------------------------------
### Redis Session Store Installation
Source: https://docs.mcp-use.com/typescript/server/configuration
Install the Redis client for use with RedisSessionStore.
```bash
npm install redis
```
--------------------------------
### Example: Connect to Server and Select Tab
Source: https://docs.mcp-use.com/inspector/url-parameters
An example URL showing how to connect to a specific server and open the 'Tools' tab using the 'server' and 'tab' parameters.
```url
https://inspector.mcp-use.com/inspect?server=https://your-server.com/mcp&tab=tools
```
--------------------------------
### Install mcp-use with uv
Source: https://docs.mcp-use.com/python/getting-started/quickstart
Install the mcp-use library and a LangChain LLM provider package using uv.
```bash
uv add mcp-use langchain-openai
```
--------------------------------
### Basic Sentiment Analyzer Server Setup
Source: https://docs.mcp-use.com/typescript/server/sampling
Sets up a basic MCP server with a sentiment analysis tool. This example demonstrates the core structure of an MCP server and a tool that uses `ctx.sample` to get LLM output.
```typescript
import { MCPServer, text } from 'mcp-use/server';
import { z } from 'zod';
const server = new MCPServer({
name: 'sentiment-analyzer',
version: '1.0.0',
});
server.tool({
name: 'analyze-sentiment',
description: 'Analyze sentiment using client\'s LLM',
schema: z.object({
text: z.string(),
})
}, async (params, ctx) => {
const prompt = `Analyze the sentiment of the following text as positive, negative, or neutral.
Just output a single word - 'positive', 'negative', or 'neutral'.
Text to analyze: ${params.text}`;
const response = await ctx.sample(prompt);
const sentiment = response.content[0].text.trim().toLowerCase();
return text(`Sentiment: ${sentiment}`);
});
await server.listen();
```
--------------------------------
### run_install
Source: https://docs.mcp-use.com/python/api-reference/mcp_use_server_templates_cli
Executes an installer command and captures its output. This function returns True if the installation is successful.
```APIDOC
## run_install
### Description
Run the installer, capturing output. Returns True on success.
### Parameters
#### Request Body
- **name** (str) - Required - Name identifier
- **cmd** (list[str]) - Required - List of items to execute
- **target_dir** (pathlib.Path) - Required - The target directory for the installation
### Response
#### Success Response (200)
- **returns** (bool) - True if the installation was successful, False otherwise.
```
--------------------------------
### Initialize and Run MCPServer
Source: https://docs.mcp-use.com/python/changelog/1_5_0
Demonstrates how to initialize an MCPServer with custom name, version, and instructions. Includes enabling development tools and pretty-printing JSON-RPC logs. Shows how to define a tool and run the server with multiple transport options and auto-reloading.
```python
from mcp_use.server import MCPServer
server = MCPServer(
name="my-awesome-server",
version="1.0.0",
instructions="A production-ready MCP server",
debug=True, # Enable development tools
pretty_print_jsonrpc=True, # Beautiful JSON-RPC logs
)
@server.tool()
def calculate(expression: str) -> float:
"""Evaluate a mathematical expression."""
return eval(expression)
# Run with multiple transport options
server.run(
transport="streamable-http", # or "stdio", "sse"
host="0.0.0.0",
port=8000,
reload=True # Auto-reload on code changes
)
```
--------------------------------
### Install mcp-use and Langchain OpenAI
Source: https://docs.mcp-use.com/home/redirects/python
Install the mcp-use package along with a LangChain LLM provider. The example uses langchain-openai, but others like langchain-anthropic can be substituted.
```bash
pip install mcp-use langchain-openai
```
--------------------------------
### Starting a New MCPServer
Source: https://docs.mcp-use.com/python/changelog/1_5_0
Demonstrates how to initialize a new MCPServer with a name, version, and debug mode. Includes a basic tool definition and server startup.
```python
from mcp_use.server import MCPServer
server = MCPServer(
name="my-server",
version="1.0.0",
debug=True # Enable dev tools during development
)
@server.tool()
def my_tool(arg: str) -> str:
return f"Result: {arg}"
if __name__ == "__main__":
server.run(transport="streamable-http", port=8000)
```
--------------------------------
### Install Google GenAI SDK
Source: https://docs.mcp-use.com/python/integration/google
Install the Google GenAI SDK using pip. This is a prerequisite for using the adapter.
```bash
uv pip install google-genai
```
--------------------------------
### Install Mintlify CLI
Source: https://docs.mcp-use.com/python/development
Install the Mintlify CLI globally using npm to manage and preview documentation.
```bash
npm i -g mintlify
```
--------------------------------
### Basic Direct Tool Call Example
Source: https://docs.mcp-use.com/python/client/direct-tool-calls
Demonstrates how to configure MCPClient, create sessions, list tools, and call a specific tool with arguments. Ensure the MCP server is configured and sessions are initialized before calling tools.
```Python
import asyncio
from mcp_use import MCPClient
async def call_tool_example():
# Configure the MCP server
config = {
"mcpServers": {
"everything": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-everything"],
}
}
}
# Create client from configuration
client = MCPClient(config)
try:
# Initialize all configured sessions
await client.create_all_sessions()
# Get the session for a specific server
session = client.get_session("everything")
# List available tools
tools = await session.list_tools()
tool_names = [t.name for t in tools]
print(f"Available tools: {tool_names}")
# Call a specific tool with arguments
result = await session.call_tool(
name="add",
arguments={"a": 1, "b": 2}
)
# Handle the result
if getattr(result, "isError", False):
print(f"Error: {result.content}")
else:
print(f"Tool result: {result.content}")
print(f"Text result: {result.content[0].text}")
finally:
# Clean up resources
await client.close_all_sessions()
if __name__ == "__main__":
asyncio.run(call_tool_example())
```
--------------------------------
### Quick Start: Custom Middleware Example
Source: https://docs.mcp-use.com/python/client/middleware
Implement a custom middleware by subclassing `Middleware` and overriding specific hooks like `on_call_tool`. This example logs the tool name before calling the next middleware.
```python
from mcp.types import CallToolRequestParams
from mcp_use import MCPClient
from mcp_use.middleware import Middleware, MiddlewareContext, NextFunctionT
class CustomMiddleware(Middleware):
async def on_call_tool(
self, context: MiddlewareContext[CallToolRequestParams], call_next: NextFunctionT
) -> CallToolResult:
print(f"Calling tool {context.params.name}")
return await call_next(context)
config = {
"mcpServers": {
"playwright": {"command": "npx", "args": ["@playwright/mcp@latest"], "env": {"DISPLAY": ":1"}}
}
}
# MCPClient automatically prepends a default logging middleware.
# You can add your own middlewares after it.
client = MCPClient(config=config, middleware=[CustomMiddleware()])
```
--------------------------------
### Basic Deployment Example
Source: https://docs.mcp-use.com/typescript/server/cli-reference
Initiates a basic deployment of your MCP server.
```bash
# Basic deployment
mcp-use deploy
```
--------------------------------
### Start Documentation Development Server
Source: https://docs.mcp-use.com/python/development/development
Navigate to the docs directory and start the Mintlify development server to preview documentation changes locally.
```bash
cd ../../docs
mintlify dev
```
--------------------------------
### Create and Use an MCP Client
Source: https://docs.mcp-use.com/home/redirects/python
This example shows how to create an MCPClient, initialize its sessions, list available tools from a server, and call a specific tool with arguments. It demonstrates basic client-server interaction.
```python
import asyncio
from mcp_use import MCPClient
async def main():
client = MCPClient({
"mcpServers": {
"everything": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-everything"]
}
}
})
# Initialize all configured sessions
await client.create_all_sessions()
# Get the session for a specific server
session = client.get_session("everything")
# List available tools
tools = await session.list_tools()
print(f"Available tools: {[t.name for t in tools]}")
# Call a specific tool with arguments
result = await session.call_tool("add", {"a": 1, "b": 2})
print(f"Result: {result}")
# Clean up
await client.close_all_sessions()
if __name__ == "__main__":
asyncio.run(main())
```
--------------------------------
### MCPServer.tool() JSDoc Examples
Source: https://docs.mcp-use.com/typescript/changelog/changelog
JSDoc @example blocks for MCPServer.tool() now include necessary import statements and response helper names.
```typescript
import { text, object, image, markdown, html, error, widget } from "mcp-use/server";
// Example usage within JSDoc
```
--------------------------------
### Basic ErrorBoundary Usage
Source: https://docs.mcp-use.com/typescript/server/widget-components/errorboundary
Wrap your widget content with ErrorBoundary to catch errors. This example shows the basic setup without custom fallbacks.
```tsx
import { ErrorBoundary } from 'mcp-use/react';
function MyWidget() {
return (
My widget content
);
}
```
--------------------------------
### Create Starter Template Project
Source: https://docs.mcp-use.com/typescript/server/templates
Quick start command to create a new MCP server using the default starter template. Includes all MCP features and hot reload.
```bash
npx create-mcp-use-app my-server --template starter
cd my-server
npm run dev
```
--------------------------------
### Initialize MCPClient with Configuration
Source: https://docs.mcp-use.com/python/client/client-configuration
Demonstrates initializing MCPClient using either a configuration file path or a dictionary. It also shows how to create sessions, list tools, and close sessions.
```python
from mcp_use import MCPClient
# From config file
client = MCPClient("config.json")
# From dictionary
client = MCPClient({
"mcpServers": {
"playwright": {
"command": "npx",
"args": ["@playwright/mcp@latest"]
}
}
})
# Create sessions and use
await client.create_all_sessions()
session = client.get_session("playwright")
tools = await session.list_tools()
# Clean up when done
await client.close_all_sessions()
```
--------------------------------
### Manual Height Notification Example
Source: https://docs.mcp-use.com/inspector/debugging-chatgpt-apps
Demonstrates how to manually get the scroll height of a content container and notify the inspector. This is an alternative to using `McpUseProvider` with `autoSize`.
```javascript
// Manual height notification
const container = document.getElementById("widget-content");
const height = container.scrollHeight;
await window.openai.notifyIntrinsicHeight(height);
```
--------------------------------
### Start Mintlify Development Server
Source: https://docs.mcp-use.com/python/development
Navigate to the docs directory and start the Mintlify development server to preview documentation changes.
```bash
cd ../../docs
mintlify dev
```
--------------------------------
### Main Server Example with Routers
Source: https://docs.mcp-use.com/python/server/router
Sets up an MCPServer and includes the database and file operations routers. This snippet shows the main entry point for a server application, demonstrating how to include multiple routers with prefixes and run the server.
```python
# main.py
from mcp_use.server import MCPServer
from routes.database import router as db_router
from routes.files import router as files_router
server = MCPServer(
name="full-stack-server",
version="1.0.0",
instructions="A server with database and file operations",
)
server.include_router(db_router, prefix="db")
server.include_router(files_router, prefix="fs")
if __name__ == "__main__":
server.run(transport="streamable-http", debug=True)
```
--------------------------------
### Basic Structured Output Example with Zod
Source: https://docs.mcp-use.com/typescript/agent/structured-output
Illustrates how to use a Zod schema with an agent to fetch and validate structured weather information. Includes setup for client and LLM.
```typescript
import { z } from 'zod'
import { ChatOpenAI } from '@langchain/openai'
import { MCPAgent, MCPClient } from 'mcp-use'
// Define the schema using Zod
const WeatherInfo = z.object({
city: z.string().describe('City name'),
temperature: z.number().describe('Temperature in Celsius'),
condition: z.string().describe('Weather condition'),
humidity: z.number().describe('Humidity percentage')
})
// TypeScript type inferred from schema
type WeatherInfo = z.infer
async function main() {
// Setup client and agent
const client = new MCPClient({ mcpServers: {...} })
const llm = new ChatOpenAI({ model: "gpt-5.5" })
const agent = new MCPAgent({ llm, client })
// Get structured output
const weather = await agent.run({
prompt: 'Get the current weather in San Francisco',
schema: WeatherInfo
})
console.log(`Temperature in ${weather.city}: ${weather.temperature}°C`)
console.log(`Condition: ${weather.condition}`)
console.log(`Humidity: ${weather.humidity}%`)
await client.closeAllSessions()
}
main().catch(console.error)
```
--------------------------------
### Run Elicitation Example Server
Source: https://docs.mcp-use.com/typescript/server/elicitation
Instructions to set up and run a complete working example of elicitation on the server. This includes form mode, URL mode, and conformance tests.
```bash
cd libraries/typescript/packages/mcp-use/examples/server/elicitation
pnpm install
pnpm dev
```
--------------------------------
### Quick Start: Google OAuth Proxy Setup
Source: https://docs.mcp-use.com/typescript/server/authentication/providers/oauth-proxy
Sets up an MCP server with Google as the OAuth provider using the oauthProxy. Ensure GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET environment variables are set.
```typescript
import { MCPServer, oauthProxy, jwksVerifier } from "mcp-use/server";
const server = new MCPServer({
name: "my-server",
version: "1.0.0",
oauth: oauthProxy({
authEndpoint: "https://accounts.google.com/o/oauth2/v2/auth",
tokenEndpoint: "https://oauth2.googleapis.com/token",
issuer: "https://accounts.google.com",
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
scopes: ["openid", "email", "profile"],
extraAuthorizeParams: { access_type: "offline" },
verifyToken: jwksVerifier({
jwksUrl: "https://www.googleapis.com/oauth2/v3/certs",
issuer: "https://www.googleapis.com/oauth2/v3/certs",
audience: process.env.GOOGLE_CLIENT_ID!,
}),
}),
});
await server.listen(3000);
```
--------------------------------
### Quick Start CLI Commands
Source: https://docs.mcp-use.com/typescript/client/cli
Connect to an MCP server and perform basic operations like listing tools.
```bash
# Connect once and save the server under a name of your choice
npx mcp-use client connect manufact https://mcp.manufact.com/mcp
# Every subsequent command names the server it operates on
npx mcp-use client manufact tools list
npx mcp-use client manufact tools call read_file path=/tmp/test.txt
npx mcp-use client manufact interactive
```
--------------------------------
### Quick Start: Connect and Call Tool
Source: https://docs.mcp-use.com/typescript/client/index
Connect to an MCP server, list tools, call a tool, and then clean up. Ensure the MCP server is running before execution.
```typescript
import { MCPClient } from 'mcp-use'
// Create client and connect
const client = new MCPClient({
mcpServers: {
'my-server': {
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-everything']
}
}
})
await client.createAllSessions()
// Get a session for a specific server
const session = client.getSession('my-server')
// List available tools
const tools = await session.listTools()
console.log('Available tools:', tools)
// Call a tool
const result = await session.callTool('tool_name', {
param: 'value'
})
console.log('Result:', result)
// Cleanup
await client.closeAllSessions()
```
--------------------------------
### Integrate LLM with MCP Agent
Source: https://docs.mcp-use.com/home
Connect various LLMs like OpenAI, Anthropic, or Google to MCP servers using the MCPAgent. This example shows basic setup with LangChain.
```python
from langchain_openai import ChatOpenAI
from mcp_use import MCPAgent, MCPClient
```
--------------------------------
### Python Prometheus Metrics for Monitoring
Source: https://docs.mcp-use.com/python/development/security
Defines Prometheus metrics (Counter, Histogram) for tracking requests, durations, and security violations. Ensure Prometheus client library is installed and metrics server is started.
```python
from prometheus_client import Counter, Histogram, start_http_server
import time
# Metrics
REQUEST_COUNT = Counter('mcp_requests_total', 'Total requests', ['user_id', 'status'])
REQUEST_DURATION = Histogram('mcp_request_duration_seconds', 'Request duration')
SECURITY_VIOLATIONS = Counter('mcp_security_violations_total', 'Security violations', ['type'])
async def monitored_agent_execution(user_id: str, query: str):
start_time = time.time()
try:
# Your existing security checks
is_valid, error = validator.validate_query(query)
if not is_valid:
SECURITY_VIOLATIONS.labels(type='invalid_query').inc()
raise ValueError(error)
allowed, message = rate_limiter.is_allowed(user_id)
if not allowed:
SECURITY_VIOLATIONS.labels(type='rate_limit').inc()
raise ValueError(message)
# Execute agent
agent = await create_secure_agent()
result = await agent.run(query)
REQUEST_COUNT.labels(user_id=user_id, status='success').inc()
return result
except Exception as e:
REQUEST_COUNT.labels(user_id=user_id, status='error').inc()
raise
finally:
REQUEST_DURATION.observe(time.time() - start_time)
# Start metrics server
start_http_server(8000)
```
--------------------------------
### Create and Use an MCP Client
Source: https://docs.mcp-use.com/typescript/getting-started
This example shows how to create an MCP Client, initialize sessions for specified MCP servers, list available tools, and call a specific tool with arguments. It uses the '@modelcontextprotocol/server-everything' as an example server.
```typescript
import { MCPClient } from 'mcp-use'
const client = new MCPClient({
mcpServers: {
everything: {
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-everything']
}
}
})
// Initialize all configured sessions
await client.createAllSessions()
// Get the session for a specific server
const session = client.getSession('everything')
// List available tools
const tools = await session.listTools()
console.log(`Available tools: ${tools.map(t => t.name).join(', ')}`)
// Call a specific tool with arguments
const result = await session.callTool(
'add',
{ a: 1, b: 2 }
)
```
--------------------------------
### Basic Structured Output Example
Source: https://docs.mcp-use.com/python/agent/structured-output
Demonstrates how to use MCPAgent to get structured output in the form of a Pydantic model. The agent will automatically retry to gather missing information until all required fields are populated.
```Python
import asyncio
from pydantic import BaseModel, Field
from langchain_openai import ChatOpenAI
from mcp_use import MCPAgent, MCPClient
class WeatherInfo(BaseModel):
"""Weather information for a location"""
city: str = Field(description="City name")
temperature: float = Field(description="Temperature in Celsius")
condition: str = Field(description="Weather condition")
humidity: int = Field(description="Humidity percentage")
async def main():
# Setup client and agent
client = MCPClient(config={"mcpServers": {...}})
llm = ChatOpenAI(model="gpt-5.5")
agent = MCPAgent(llm=llm, client=client)
# Get structured output
weather: WeatherInfo = await agent.run(
"Get the current weather in San Francisco",
output_schema=WeatherInfo
)
print(f"Temperature in {weather.city}: {weather.temperature}°C")
print(f"Condition: {weather.condition}")
print(f"Humidity: {weather.humidity}%")
asyncio.run(main())
```
--------------------------------
### Quick Start: Custom OAuth Provider Setup
Source: https://docs.mcp-use.com/typescript/server/authentication/providers/custom
Sets up an MCP server with a custom OAuth provider supporting Dynamic Client Registration. Includes JWT verification using the `jose` library.
```typescript
import { MCPServer, oauthCustomProvider } from "mcp-use/server";
import { jwtVerify, createRemoteJWKSet } from "jose";
const JWKS = createRemoteJWKSet(
new URL("https://auth.example.com/.well-known/jwks.json"),
);
const server = new MCPServer({
name: "my-server",
version: "1.0.0",
oauth: oauthCustomProvider({
issuer: "https://auth.example.com",
authEndpoint: "https://auth.example.com/oauth/authorize",
tokenEndpoint: "https://auth.example.com/oauth/token",
async verifyToken(token: string) {
const result = await jwtVerify(token, JWKS, {
issuer: "https://auth.example.com",
audience: "your-audience",
});
return { payload: result.payload as Record };
},
getUserInfo(payload) {
return {
userId: payload.sub as string,
email: payload.email as string | undefined,
name: payload.name as string | undefined,
roles: (payload.roles as string[]) || [],
};
},
}),
});
await server.listen(3000);
```
--------------------------------
### STDIO Server Configuration Example
Source: https://docs.mcp-use.com/typescript/client/client-configuration
Example of configuring a server that runs as a local child process using STDIO. Includes command, arguments, environment variables, and client information.
```json
{
"mcpServers": {
"stdio_server": {
"command": "npx",
"args": ["@my-mcp/server"],
"env": {},
"clientInfo": {
"name": "My Custom Client",
"title": "My Custom Client Display Name",
"version": "1.0.0"
}
}
}
}
```
--------------------------------
### Get create-mcp-use-app Help
Source: https://docs.mcp-use.com/typescript/server/templates
Run this command to view all available templates and options for the create-mcp-use-app CLI tool.
```bash
npx create-mcp-use-app --help
```
--------------------------------
### Scaffold a New MCP Server Project
Source: https://docs.mcp-use.com/home/redirects/python
Use the create-mcp-use command-line tool to scaffold a new MCP server project. This command is available via uvx or if mcp-use is installed locally. After scaffolding, navigate to the project directory and start the server.
```bash
# Via uvx (from PyPI)
uvx --from mcp-use create-mcp-use my-server
# Or if mcp-use is installed locally
create-mcp-use my-server
# Start the server
cd my-server
python server.py
```
--------------------------------
### Using a Custom Adapter with MCPClient
Source: https://docs.mcp-use.com/python/agent/building-custom-agents
Demonstrates how to initialize the MCPClient, create an instance of your custom adapter, and retrieve tools for use with your agent framework.
```python
from your_module import YourFrameworkAdapter
from mcp_use.client import MCPClient
# Initialize the client
client = MCPClient.from_config_file("config.json")
# Create an adapter instance
adapter = YourFrameworkAdapter()
# Get tools with a single line
tools = await adapter.create_tools(client)
# Use the tools with your framework
agent = your_framework.create_agent(tools=tools)
```
--------------------------------
### Complete Anthropic SDK Integration with MCP
Source: https://docs.mcp-use.com/python/integration/anthropic
This example shows the full integration flow, including setting up the MCP client, creating an AnthropicMCPAdapter, converting tools, and using them with the Anthropic messages API. It handles tool calls, execution, and processing tool results to get a final model response.
```python
import asyncio
from anthropic import Anthropic
from dotenv import load_dotenv
from mcp_use import MCPClient
from mcp_use.agents.adapters import AnthropicMCPAdapter
# This example demonstrates how to use our integration
# adapters to use MCP tools and convert to the right format.
# In particularly, this example uses the AnthropicMCPAdapter.
load_dotenv()
async def main():
config = {"mcpServers": {"server": {"url": "http://127.0.0.1:8080/mcp"}}}
try:
client = MCPClient(config=config)
# Creates the adapter for Anthropic's format
adapter = AnthropicMCPAdapter()
# Convert tools from active connectors to the Anthropic's format
await adapter.create_all(client)
# List concatenation (if you loaded all tools)
anthropic_tools = adapter.tools + adapter.resources + adapter.prompts
# If you don't want to create all tools, you can call single functions
# await adapter.create_tools(client)
# await adapter.create_resources(client)
# await adapter.create_prompts(client)
# Use tools with Anthropic's SDK (not agent in this case)
anthropic = Anthropic()
# Initial request
messages = [{"role": "user", "content": "Please could you give me the assistant prompt? My name is vincenzo"}]
response = anthropic.messages.create(
model="claude-opus-4-7", tools=anthropic_tools, max_tokens=1024, messages=messages
)
messages.append({"role": response.role, "content": response.content})
print("Claude wants to use tools:", response.stop_reason == "tool_use")
print("Number of tool calls:", len([c for c in response.content if c.type == "tool_use"]))
if response.stop_reason == "tool_use":
tool_results = []
for c in response.content:
if c.type != "tool_use":
continue
tool_name = c.name
arguments = c.input
# Use the adapter's map to get the correct executor
executor = adapter.tool_executors.get(tool_name)
if not executor:
print(f"Error: Unknown tool '{tool_name}' requested by model.")
content = f"Error: Tool '{tool_name}' not found."
else:
try:
# Execute the tool using the retrieved function
print(f"Executing tool: {tool_name}({arguments})")
tool_result = await executor(**arguments)
# Use the adapter's universal parser
content = adapter.parse_result(tool_result)
except Exception as e:
print(f"An unexpected error occurred while executing tool {tool_name}: {e}")
content = f"Error executing tool: {e}"
# Append the result for this specific tool call
tool_results.append(
{
"type": "tool_result",
"tool_use_id": c.id,
"content": content,
}
)
if tool_results:
messages.append(
{
"role": "user",
"content": tool_results,
}
)
# Get final response
final_response = anthropic.messages.create(
model="claude-opus-4-7", max_tokens=1024, tools=anthropic_tools, messages=messages
)
print("\n--- Final response from the model ---")
print(final_response.content[0].text)
else:
final_response = response
print("\n--- Final response from the model ---")
if final_response.content:
print(final_response.content[0].text)
except Exception as e:
print(f"Error: {e}")
raise e
if __name__ == "__main__":
asyncio.run(main())
```
--------------------------------
### Initialize MCPServer
Source: https://docs.mcp-use.com/python/server/index
Create a new MCPServer instance with basic configuration like name, version, and instructions.
```python
from mcp_use.server import MCPServer
server = MCPServer(
name="My Server",
version="1.0.0",
instructions="A simple example server"
)
```
--------------------------------
### Install Langfuse and Laminar Packages
Source: https://docs.mcp-use.com/python/agent/observability
Install the necessary packages for Langfuse and Laminar observability. Ensure these are installed to avoid 'Package not installed' errors.
```bash
# Install the required packages
pip install langfuse # For Langfuse
pip install lmnr # For Laminar
```
--------------------------------
### mcp-use Project Setup Command
Source: https://docs.mcp-use.com/guides/chatgpt-apps-flow
Use this command to create a new mcp-use application with the mcp-apps template.
```bash
npx create-mcp-use-app my-app --template mcp-apps
```
--------------------------------
### Create a Custom Agent with LangChain Adapter
Source: https://docs.mcp-use.com/python/agent/building-custom-agents
This example demonstrates how to initialize an MCP client, create a LangChain adapter, generate LangChain-compatible tools from MCP tools, initialize a language model, and create/run a LangChain agent. Ensure you have a configuration file at 'path/to/config.json'.
```Python
import asyncio
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from mcp_use.client import MCPClient
from mcp_use.adapters import LangChainAdapter
async def main():
# Initialize the MCP client
client = MCPClient.from_config_file("path/to/config.json")
# Create adapter instance
adapter = LangChainAdapter()
# Get LangChain tools directly from the client with a single line
tools = await adapter.create_tools(client)
# Initialize your language model
model = init_chat_model("gpt-5.5", temperature=0.5)
# Create the agent
agent = create_agent(
model=model,
tools=tools,
system_prompt="You are a helpful assistant with access to powerful tools.",
)
# Run the agent
result = await agent.ainvoke(
{"messages": [{"role": "user", "content": "What can you do?"}]}
)
print(result)
if __name__ == "__main__":
asyncio.run(main())
```
--------------------------------
### detect_installer
Source: https://docs.mcp-use.com/python/api-reference/mcp_use_server_templates_cli
Detects the best available package installer for the system. Returns the name of the installer and its installation command.
```APIDOC
## detect_installer
### Description
Detects the best available package installer. Returns the installer name and its installation command.
### Returns
- **returns** (tuple[str, list[str]]) - A tuple containing the installer name and a list of strings representing the installation command.
### Signature
```python
def detect_installer():
```
```
--------------------------------
### Create and Run an MCP Agent with Browser Tools
Source: https://docs.mcp-use.com/typescript/getting-started
This example demonstrates how to create an MCP Agent using a LangChain LLM and the MCP Client with browser tool support. It shows how to initialize the client, configure the agent, run a query, and clean up sessions.
```typescript
import { ChatOpenAI } from '@langchain/openai' // use your preferred LLM provider
import { MCPAgent, MCPClient } from 'mcp-use'
// Create MCPClient from configuration object
const client = new MCPClient({
mcpServers: {
playwright: {
command: 'npx',
args: ['@playwright/mcp@latest'],
env: {
DISPLAY: ':1'
}
}
}
})
// Create agent with the client
const agent = new MCPAgent({
llm: new ChatOpenAI({ model: "gpt-5.5" }), // use your preferred LLM provider
client,
maxSteps: 30
})
// Run the query
const result = await agent.run({
prompt: 'Find the best restaurant in San Francisco USING GOOGLE SEARCH'
})
console.log(`\nResult: ${result}`)
// Clean up
await client.closeAllSessions()
```
--------------------------------
### Detect Installer Function Signature
Source: https://docs.mcp-use.com/python/api-reference/mcp_use_server_templates_cli
Defines the signature for the detect_installer function, which returns the name and installation command of the detected package installer.
```python
def detect_installer():
```
--------------------------------
### Import display_startup_info
Source: https://docs.mcp-use.com/python/api-reference/mcp_use_server_logging_startup
Import the display_startup_info function from the mcp_use.server.logging.startup module.
```python
from mcp_use.server.logging.startup import display_startup_info
```
--------------------------------
### Install @mcp-use/cli Globally or with npx
Source: https://docs.mcp-use.com/typescript/server/cli-reference
Install the CLI globally for system-wide access or use npx to run commands without a local installation.
```bash
npm install -g @mcp-use/cli
```
```bash
npx @mcp-use/cli dev
```