### Initialize TypeScript Project and Install Dev Dependencies
Source: https://docs.mcp-use.com/typescript/server/getting-started
This command initializes a new Node.js project with npm, installs TypeScript, its Node.js types, and tsx for running TypeScript files during development. These are essential for setting up a TypeScript-based project.
```bash
mkdir my-mcp-server
cd my-mcp-server
npm init -y
npm install typescript @types/node tsx --save-dev
```
--------------------------------
### MCP Server Framework - Quick Start Example
Source: https://docs.mcp-use.com/typescript/server/index
A minimal example demonstrating how to set up and run an MCP server with a simple tool and resource.
```APIDOC
## Quick Start Example
This example shows a minimal setup for an MCP server.
### Method
```typescript
import { createMCPServer } from 'mcp-use/server'
// Create server instance
const server = createMCPServer('my-mcp-server', {
version: '1.0.0',
description: 'My first MCP server'
})
// Define a simple tool
server.tool({
name: 'greet',
description: 'Greet someone by name',
inputs: [
{ name: 'name', type: 'string', required: true }
],
cb: async ({ name }) => {
return {
content: [
{
type: 'text',
text: `Hello, ${name}! Welcome to MCP.`
}
]
}
}
})
// Define a resource
server.resource({
name: 'config',
uri: 'config://settings',
mimeType: 'application/json',
description: 'Server configuration',
readCallback: async () => ({
contents: [{
uri: 'config://settings',
mimeType: 'application/json',
text: JSON.stringify({
theme: 'dark',
language: 'en'
})
}]
})
})
// Start the server
server.listen(3000)
```
### Server Endpoints
* **MCP Endpoint**: `http://localhost:3000/mcp` - For MCP client connections
* **Inspector UI**: `http://localhost:3000/inspector` - Development and testing interface (if `@mcp-use/inspector` is installed)
```
--------------------------------
### Load MCP Client Configuration from File in TypeScript
Source: https://docs.mcp-use.com/typescript/getting-started/quickstart
This example demonstrates how to load MCP server configurations from a JSON file using `loadConfigFile` and then instantiate an MCPClient with the loaded configuration. This is useful for managing complex server setups.
```typescript
import { loadConfigFile } from 'mcp-use'
const config = await loadConfigFile("browser_mcp.json")
const client = new MCPClient(config)
```
--------------------------------
### Install MCP Server Framework and Inspector
Source: https://docs.mcp-use.com/typescript/server/getting-started
Installs the core mcp-use server framework, which is necessary for building MCP servers. It also installs the inspector tool as a development dependency, useful for debugging and inspecting server behavior.
```bash
npm install mcp-use
npm install --save-dev @mcp-use/inspector
```
--------------------------------
### Run MCP Development Server
Source: https://docs.mcp-use.com/typescript/getting-started/quickstart
Starts the development server for an MCP project. Once running, the server is ready to accept connections from MCP clients.
```bash
npm run dev
```
--------------------------------
### Minimal mcp-use Server Example in TypeScript
Source: https://docs.mcp-use.com/typescript/server/index
A basic example demonstrating how to create an MCP server using the mcp-use framework in TypeScript. It includes defining a simple tool, a resource, and starting the server.
```typescript
import { createMCPServer } from 'mcp-use/server'
// Create server instance
const server = createMCPServer('my-mcp-server', {
version: '1.0.0',
description: 'My first MCP server'
})
// Define a simple tool
server.tool({
name: 'greet',
description: 'Greet someone by name',
inputs: [
{ name: 'name', type: 'string', required: true }
],
cb: async ({ name }) => {
return {
content: [
{
type: 'text',
text: `Hello, ${name}! Welcome to MCP.`
}
]
}
}
})
// Define a resource
server.resource({
name: 'config',
uri: 'config://settings',
mimeType: 'application/json',
description: 'Server configuration',
readCallback: async () => ({
contents: [{
uri: 'config://settings',
mimeType: 'application/json',
text: JSON.stringify({
theme: 'dark',
language: 'en'
})
}]
})
})
// Start the server
server.listen(3000)
```
--------------------------------
### MCP Development Workflow: Setup and Component Creation (Bash & TSX)
Source: https://docs.mcp-use.com/typescript/server/mcp-ui-resources
Outlines the initial steps in the MCP widget development workflow. This includes setting up the development environment using npm for dependency installation and starting the development server, followed by creating a basic React widget component in TypeScript/JSX. Requires Node.js and npm.
```bash
# Install dependencies
npm install
# Start development server
npm run dev
```
```tsx
// resources/my-widget.tsx
import React from 'react'
export default function MyWidget() {
return (
My Widget
{/* Widget implementation */}
)
}
```
--------------------------------
### Usage Example for Development Workflow (TypeScript)
Source: https://docs.mcp-use.com/typescript/advanced/multi-server-setup
This TypeScript example illustrates an agent executing a development workflow task. The task involves creating a Python function, writing and running unit tests, and committing changes if tests pass. This relies on a pre-configured environment with filesystem, GitHub, Python, and Git servers.
```typescript
const result = await agent.run(
'Create a new Python function to calculate fibonacci numbers, '
)
```
--------------------------------
### MCP Client Configuration (JSON)
Source: https://docs.mcp-use.com/typescript/server/getting-started
Configuration example for an MCP client to connect to the weather server. This JSON object specifies the server URL under the 'mcpServers' key.
```json
{
"mcpServers": {
"weather-server": {
"url": "http://localhost:3000/mcp"
}
}
}
```
--------------------------------
### Create MCP Server using npm, pnpm, or yarn
Source: https://docs.mcp-use.com/typescript/getting-started/quickstart
Scaffolds a new MCP server project using a create-mcp-use-app command. It sets up a TypeScript project with pre-configured build tools and installs necessary dependencies. The command helps in initializing a basic MCP server structure.
```bash
npx create-mcp-use-app@latest my-mcp-server
cd my-mcp-server
npm run dev
```
```bash
pnpm create mcp-use-app@latest my-mcp-server
cd my-mcp-server
pnpm run dev
```
```bash
yarn create mcp-use-app@latest my-mcp-server
cd my-mcp-server
yarn dev
```
--------------------------------
### Create Basic MCP Server Instance in TypeScript
Source: https://docs.mcp-use.com/typescript/server/getting-started
This TypeScript code defines the basic structure of an MCP server using the `createMCPServer` function from the 'mcp-use/server' library. It initializes the server with a name and version, and sets it up to listen on a specified port.
```typescript
import { createMCPServer } from 'mcp-use/server'
// Create the server instance
const server = createMCPServer('weather-mcp-server', {
version: '1.0.0',
description: 'A weather information MCP server'
})
// Start the server
const PORT = process.env.PORT ? parseInt(process.env.PORT) : 3000
server.listen(PORT).then(() => {
console.log(`Server running on port ${PORT}`)
})
```
--------------------------------
### Install mcp-use Package
Source: https://docs.mcp-use.com/typescript/server
Installs the mcp-use package for manual setup or integration into an existing project. For development and testing, the optional inspector UI can also be installed.
```bash
npm install mcp-use
```
```bash
npm install --save-dev @mcp-use/cli
```
--------------------------------
### Create MCP Server with TypeScript
Source: https://docs.mcp-use.com/typescript/server/getting-started
This code snippet initializes an MCP server using the 'mcp-use/server' library in TypeScript. It sets up basic server configuration, defines mock weather data, and registers a 'get_weather' tool and a 'weather_alerts' resource. It also includes an HTTP health endpoint and starts the server listening on a specified port.
```typescript
import { createMCPServer } from 'mcp-use/server'
import express from 'express'
// Mock weather data
const weatherData: Record = {
'new-york': { temp: 72, condition: 'Partly cloudy', humidity: 65 },
'london': { temp: 59, condition: 'Rainy', humidity: 80 },
'tokyo': { temp: 78, condition: 'Sunny', humidity: 55 },
'paris': { temp: 64, condition: 'Overcast', humidity: 70 }
}
// Create server
const server = createMCPServer('weather-mcp-server', {
version: '1.0.0',
description: 'A weather information MCP server'
})
// Add weather lookup tool
server.tool({
name: 'get_weather',
description: 'Get current weather for a city',
inputs: [
{
name: 'city',
type: 'string',
description: 'City name',
required: true
}
],
cb: async ({ city }) => {
const cityKey = city.toLowerCase().replace(' ', '-')
const data = weatherData[cityKey]
if (!data) {
return {
content: [{
type: 'text',
text: `Weather data not available for ${city}`
}]
}
}
return {
content: [{
type: 'text',
text: `Weather in ${city}:\n` +
`Temperature: ${data.temp}°F\n` +
`Condition: ${data.condition}\n` +
`Humidity: ${data.humidity}%`
}]
}
}
})
// Add alerts resource
server.resource({
name: 'weather_alerts',
uri: 'weather://alerts',
title: 'Current Weather Alerts',
mimeType: 'application/json',
readCallback: async () => ({
contents: [{
uri: 'weather://alerts',
mimeType: 'application/json',
text: JSON.stringify([
{
type: 'warning',
title: 'Heavy Rain Warning',
areas: ['London']
}
], null, 2)
}]
})
})
// Add health endpoint
server.get('/health', (req, res) => {
res.json({ status: 'healthy' })
})
// Start server
const PORT = 3000
server.listen(PORT).then(() => {
console.log(`Weather MCP Server running on port ${PORT}`)
console.log(`MCP endpoint: http://localhost:${PORT}/mcp`)
console.log(`Inspector: http://localhost:${PORT}/inspector`)
})
```
--------------------------------
### Add Scripts to package.json for Development and Production
Source: https://docs.mcp-use.com/typescript/server/getting-started
This JSON snippet adds scripts to the package.json file for managing the server. 'dev' uses tsx for hot-reloading development, 'build' compiles TypeScript to JavaScript using tsc, and 'start' runs the compiled JavaScript server.
```json
{
"type": "module",
"scripts": {
"dev": "tsx watch src/index.ts",
"build": "tsc",
"start": "node dist/index.js"
}
}
```
--------------------------------
### Build and Start Production Server with npm
Source: https://docs.mcp-use.com/typescript/server/ui-widgets
These commands are used to prepare the project for production deployment. `npm run build` creates optimized production bundles for all widgets, and `npm start` launches the production server to serve these widgets.
```bash
npm run build
npm start
```
--------------------------------
### Initialize MCP Server with Basic Configuration
Source: https://docs.mcp-use.com/typescript/server/configuration
Demonstrates the basic setup of an MCP server instance by providing initial configuration options such as version and description directly during creation.
```typescript
import { createMCPServer } from 'mcp-use/server'
const server = createMCPServer('my-server', {
version: '1.0.0', // Semantic version
description: 'Server purpose' // Human-readable description
})
```
--------------------------------
### Development Installation of mcp-use from Source
Source: https://docs.mcp-use.com/typescript/getting-started/installation
Install mcp-use from source for development purposes or to use the latest features. This involves cloning the repository, navigating to the TypeScript libraries directory, and installing/building the project.
```bash
git clone https://github.com/mcp-use/mcp-use.git
cd mcp-use/libraries/typescript
pnpm install
pnpm run build
```
--------------------------------
### Add Prompts for AI Models in TypeScript
Source: https://docs.mcp-use.com/typescript/server/getting-started
Create prompts to generate structured inputs for AI models. This involves defining a prompt with a name, description, arguments, and a callback function that constructs the messages for the AI.
```typescript
server.prompt({
name: 'weather_analysis',
description: 'Generate a weather analysis prompt',
args: [
{
name: 'city',
type: 'string',
required: true
},
{
name: 'days',
type: 'number',
required: false
}
],
cb: async ({ city, days = 7 }) => {
return {
messages: [
{
role: 'system',
content: 'You are a professional meteorologist providing weather analysis.'
},
{
role: 'user',
content: `Please provide a detailed weather analysis for ${city} ` +
`covering the next ${days} days. Include temperature trends, ` +
`precipitation probability, and any notable weather patterns.`
}
]
}
}
})
```
--------------------------------
### Enable Detailed Logging for Server Startup
Source: https://docs.mcp-use.com/typescript/advanced/multi-server-setup
Addresses server startup failures by enabling detailed logging. Ensure all dependencies are installed. This code snippet initializes the logger to 'debug' level and loads configuration to create an MCP client.
```typescript
import { logger } from 'mcp-use'
// Enable detailed logging
logger.level = 'debug'
const config = await loadConfigFile('config.json')
const client = new MCPClient(config)
```
```typescript
import { logger } from 'mcp-use'
// Enable detailed logging
logger.level = 'debug'
const config = await loadConfigFile('config.json')
const client = new MCPClient(config)
```
--------------------------------
### Create MCP Server Project using npm, pnpm, or yarn
Source: https://docs.mcp-use.com/typescript/getting-started/installation
Scaffold a new MCP server project using create-mcp-use-app. This command initializes a TypeScript project with mcp-use configured, sets up a basic server template, and installs dependencies.
```bash
npx create-mcp-use-app my-mcp-server
cd my-mcp-server
npm run dev
```
```bash
pnpm create mcp-use-app my-mcp-server
cd my-mcp-server
pnpm run dev
```
```bash
yarn create mcp-use-app my-mcp-server
cd my-mcp-server
yarn dev
```
--------------------------------
### Verify mcp-use Installation
Source: https://docs.mcp-use.com/typescript/getting-started/installation
Verify the installation of mcp-use by importing MCPAgent and MCPClient and logging a success message. This ensures that the library is correctly set up in your TypeScript project.
```typescript
import { MCPAgent, MCPClient } from 'mcp-use'
console.log('mcp-use installed successfully!')
```
--------------------------------
### Install mcp-use as a Library using npm, pnpm, or yarn
Source: https://docs.mcp-use.com/typescript/getting-started/installation
Install mcp-use as a library for MCP agents using your preferred package manager. This is followed by installing a LangChain provider like @langchain/openai and dotenv.
```bash
npm install mcp-use
```
```bash
pnpm add mcp-use
```
```bash
yarn add mcp-use
```
--------------------------------
### Example Express.js Application Setup in TypeScript
Source: https://docs.mcp-use.com/typescript/server/api-reference
Provides a comprehensive example of setting up an Express.js server in TypeScript. It includes essential middleware for body parsing (`express.json()`, `express.urlencoded()`), a custom logging middleware, a basic API route for status checks, and a generic error handling middleware.
```typescript
import express from 'express'
// Body parsing middleware
server.use(express.json())
server.use(express.urlencoded({ extended: true }))
// Custom middleware
server.use((req, res, next) => {
console.log(`${req.method} ${req.path}`)
next()
})
// API routes
server.get('/api/status', (req, res) => {
res.json({ status: 'ok' })
})
// Error handling
server.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).send('Something broke!')
})
```
--------------------------------
### Compose Tools for Data Fetching and Analysis in TypeScript
Source: https://docs.mcp-use.com/typescript/server/tools
This example illustrates tool composition, showing how different tools can work together. It includes a tool to fetch user data and another to analyze it, demonstrating a common pattern for data-driven operations.
```typescript
// Data fetching tool
server.tool({
name: 'fetch_user',
description: 'Fetch user data',
inputs: [
{ name: 'userId', type: 'string', required: true }
],
cb: async ({ userId }) => {
const user = await getUserFromDatabase(userId)
return {
content: [{
type: 'text',
text: JSON.stringify(user)
}]
}
}
})
// Analysis tool that uses fetched data
server.tool({
name: 'analyze_user',
description: 'Analyze user activity',
inputs: [
{ name: 'userId', type: 'string', required: true }
],
cb: async ({ userId }) => {
// Could call fetch_user first or expect client to provide data
const userData = await getUserFromDatabase(userId)
const analysis = analyzeUserActivity(userData)
return {
content: [{
type: 'text',
text: `User ${userId} analysis:\n${analysis}`
}]
}
}
})
```
--------------------------------
### Configure TypeScript Compiler Options
Source: https://docs.mcp-use.com/typescript/server/getting-started
This JSON configuration file sets up the TypeScript compiler. It specifies target ECMAScript version, module system, module resolution strategy, and other compiler options like strict type checking and output directory. This ensures consistent compilation behavior.
```json
{
"compilerOptions": {
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "node",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
```
--------------------------------
### Example MCP Server Configuration
Source: https://docs.mcp-use.com/typescript/client/client-configuration
A basic example of an MCP server configuration in JSON format, specifying a server named 'my_server' using 'npx' to run a command with arguments and environment variables.
```json
{
"mcpServers": {
"my_server": {
"command": "npx",
"args": ["@my-mcp/server"],
"env": {
"PORT": "3000"
}
}
}
}
```
--------------------------------
### Install LangChain Provider and dotenv
Source: https://docs.mcp-use.com/typescript/getting-started/installation
Install a LangChain provider and the dotenv package to manage environment variables. This is typically done after installing mcp-use as a library for agents.
```bash
npm install @langchain/openai dotenv
```
```bash
pnpm add @langchain/openai dotenv
```
```bash
yarn add @langchain/openai dotenv
```
--------------------------------
### Integrate with OpenAI Apps SDK using TypeScript
Source: https://docs.mcp-use.com/typescript/server/tools
This example demonstrates integrating tools with OpenAI compatible clients, such as ChatGPT. It uses the `_meta` field to specify UI templates and provide invocation feedback messages.
```typescript
server.tool({
name: 'show_chart',
description: 'Display a chart',
inputs: [
{ name: 'data', type: 'array', required: true }
],
_meta: {
'openai/outputTemplate': 'ui://widgets/chart',
'openai/toolInvocation/invoking': 'Generating chart...',
'openai/toolInvocation/invoked': 'Chart generated',
'openai/widgetAccessible': true
},
cb: async ({ data }) => {
return {
_meta: {
'openai/outputTemplate': 'ui://widgets/chart'
},
content: [{
type: 'text',
text: 'Chart displayed'
}],
structuredContent: { data }
}
}
})
```
--------------------------------
### Configuration for Research and Documentation (JSON)
Source: https://docs.mcp-use.com/typescript/advanced/multi-server-setup
This JSON configuration defines MCP servers for research and documentation tasks, including web browsing with Playwright, accessing ArXiv and Wikipedia, and managing files. This setup enables an agent to gather information, process it, and save notes. It may require specific server installations like '@playwright/mcp'.
```json
{
"mcpServers": {
"playwright": {
"command": "npx",
"args": ["@playwright/mcp@latest"]
},
"arxiv": {
"command": "mcp-server-arxiv",
"args": ["--max-results", "10"]
},
"wikipedia": {
"command": "mcp-server-wikipedia",
"args": ["--language", "en"]
},
"filesystem": {
"command": "mcp-server-filesystem",
"args": ["/research/notes"]
}
}
}
```
--------------------------------
### Verify mcp-use Installation with TypeScript
Source: https://docs.mcp-use.com/typescript/getting-started/installation
This snippet verifies the mcp-use installation by initializing MCPClient, ChatOpenAI, and MCPAgent. It requires the 'dotenv', '@langchain/openai', and 'mcp-use' packages. The function configures a simple test server and logs success messages or errors.
```typescript
import { config } from 'dotenv'
import { ChatOpenAI } from '@langchain/openai'
import { MCPAgent, MCPClient } from 'mcp-use'
async function verifyInstallation() {
config()
// Simple configuration for testing
const configuration = {
mcpServers: {
test: {
command: 'echo',
args: ['Hello from MCP!']
}
}
}
try {
const client = new MCPClient(configuration)
console.log('✅ MCPClient created successfully')
const llm = new ChatOpenAI({ model: 'gpt-3.5-turbo' })
console.log('✅ LLM initialized successfully')
const agent = new MCPAgent({ llm, client })
console.log('✅ MCPAgent created successfully')
console.log('
🎉 Installation verified! You\'re ready to use mcp_use.')
// Clean up
await client.closeAllSessions()
} catch (error) {
console.error('❌ Verification failed:', error)
console.error('Please check your installation and API keys.')
}
}
verifyInstallation().catch(console.error)
```
--------------------------------
### Development Workflow Usage Example (TypeScript)
Source: https://docs.mcp-use.com/typescript/client/multi-server-setup
This TypeScript snippet demonstrates using an MCPAgent for a development workflow. It involves creating a Python function, writing unit tests, running them, and committing changes if tests pass. This requires the configured development MCP servers.
```typescript
const result = await agent.run(
'Create a new Python function to calculate fibonacci numbers, '
'write unit tests for it, run the tests, '
'and if they pass, commit the changes to the current git branch'
)
```
--------------------------------
### Basic Multi-Server Agent Setup (TypeScript)
Source: https://docs.mcp-use.com/typescript/advanced/multi-server-setup
This TypeScript code demonstrates the basic setup for an MCPAgent using multiple MCP servers. It loads a multi-server configuration file, initializes an MCPClient, and then creates an MCPAgent that has access to all configured servers. The agent can then execute complex tasks involving tools from different servers.
```typescript
import { ChatOpenAI } from '@langchain/openai'
import { MCPAgent, MCPClient, loadConfigFile } from 'mcp-use'
async function main() {
// Load multi-server configuration
const config = await loadConfigFile('multi_server_config.json')
const client = new MCPClient(config)
// Create agent (all servers will be connected)
const llm = new ChatOpenAI({ model: 'gpt-4' })
const agent = new MCPAgent({ llm, client })
// Agent has access to tools from all servers
const result = await agent.run(
'Search for Python tutorials online, save the best ones to a file, ' +
'then create a database table to track my learning progress'
)
console.log(result)
await client.closeAllSessions()
}
main().catch(console.error)
```
--------------------------------
### Create MCP Apps SDK Project and Start Dev Server
Source: https://docs.mcp-use.com/typescript/server/ui-widgets
This command initializes a new MCP project using the 'apps-sdk' template, which includes automatic widget registration. It then navigates into the project directory and starts the development server.
```bash
npx create-mcp-use-app my-mcp-server --template apps-sdk
cd my-mcp-server
npm run dev
```
--------------------------------
### Add Dynamic Resource Templates in TypeScript
Source: https://docs.mcp-use.com/typescript/server/getting-started
Dynamically generate content based on URI parameters using resource templates. This method requires defining a resource template with a URI template and a read callback function to fetch and format data.
```typescript
server.resourceTemplate({
name: 'city_weather',
resourceTemplate: {
uriTemplate: 'weather://city/{cityName}',
name: 'City Weather Data',
mimeType: 'application/json'
},
readCallback: async (uri, params) => {
const cityKey = params.cityName.toLowerCase().replace(' ', '-')
const data = weatherData[cityKey]
if (!data) {
return {
contents: [{
uri: uri.toString(),
mimeType: 'application/json',
text: JSON.stringify({ error: `No data for ${params.cityName}` })
}]
}
}
return {
contents: [{
uri: uri.toString(),
mimeType: 'application/json',
text: JSON.stringify({
city: params.cityName,
...data,
timestamp: new Date().toISOString()
}, null, 2)
}]
}
}
})
```
--------------------------------
### Example .env File for MCP and LLM Configuration (Bash)
Source: https://docs.mcp-use.com/typescript/advanced/security
This example shows a secure `.env` file structure for managing API keys and configuration settings for LLM providers and MCP servers. It includes placeholders for sensitive keys and configuration parameters like filesystem roots, database URLs, and security settings. Proper management of this file is critical, as it should never be committed to version control.
```bash
# LLM Provider Keys
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
GROQ_API_KEY=gsk_...
# MCP Server Configuration
FILESYSTEM_ROOT=/safe/workspace
DATABASE_URL=postgresql://user:pass@localhost/db
# Optional: Security settings
MCP_TIMEOUT=30
MAX_TOOL_CALLS=10
ALLOWED_DOMAINS=example.com,api.service.com
```
--------------------------------
### Read Resource Example in TypeScript
Source: https://docs.mcp-use.com/typescript/client/resources
Demonstrates how to read a resource by its URI using MCPClient. It initializes the client, gets a session, reads the resource, and iterates through its contents, handling different MIME types like JSON, plain text, and binary data. Remember to configure your mcpServers in the config.
```typescript
import { MCPClient } from 'mcp-use'
async function readResourceExample() {
const config = {
mcpServers: {
// Your server definitions here
}
}
const client = new MCPClient(config)
await client.createAllSessions()
const session = client.getSession('file_server')
// Read a resource by URI
const resourceUri = 'file:///path/to/config.json'
const result = await session.readResource(resourceUri)
// Handle the result
for (const content of result.contents) {
if (content.mimeType === 'application/json') {
console.log(`JSON content: ${content.text}`)
} else if (content.mimeType === 'text/plain') {
console.log(`Text content: ${content.text}`)
} else {
console.log(`Binary content length: ${content.blob?.length}`)
}
}
await client.closeAllSessions()
}
readResourceExample().catch(console.error)
```
--------------------------------
### Development Setup with dotenv and JSON config in TypeScript
Source: https://docs.mcp-use.com/typescript/getting-started/configuration
Configures the mcp-use environment for development using dotenv for environment variables and loading a JSON configuration file. This setup initializes both MCPClient and MCPAgent with specific settings like max steps and verbose logging.
```typescript
// Simple development configuration
import { config } from 'dotenv'
import { loadConfigFile, MCPAgent, MCPClient } from 'mcp-use'
import { ChatOpenAI } from '@langchain/openai'
config()
const configuration = await loadConfigFile('dev-config.json')
const client = new MCPClient(configuration)
const agent = new MCPAgent({
llm: new ChatOpenAI({ model: 'gpt-4o' }),
client,
maxSteps: 10,
verbose: true
})
```
```typescript
// Simple development configuration
import { config } from 'dotenv'
import { loadConfigFile, MCPAgent, MCPClient } from 'mcp-use'
import { ChatOpenAI } from '@langchain/openai'
config()
const configuration = await loadConfigFile('dev-config.json')
const client = new MCPClient(configuration)
const agent = new MCPAgent({
llm: new ChatOpenAI({ model: 'gpt-4o' }),
client,
maxSteps: 10,
verbose: true
})
```
--------------------------------
### Check Node.js Executable Path (Bash)
Source: https://docs.mcp-use.com/typescript/getting-started/installation
This command checks the system's PATH for the 'npx' executable, which is part of Node.js. This is useful for ensuring that Node.js and its associated tools are correctly installed and accessible, which is often a prerequisite for running server-based applications.
```bash
which npx
```
--------------------------------
### View create-mcp-use-app options
Source: https://docs.mcp-use.com/typescript/getting-started/quickstart
Displays help information for the create-mcp-use-app command, allowing users to explore available templates and configuration options for scaffolding new MCP server projects.
```bash
npx create-mcp-use-app --help
```
--------------------------------
### Quick Start Starter Template (TypeScript)
Source: https://docs.mcp-use.com/typescript/server/templates
Commands to create an MCP server using the default 'starter' template and then demonstrates TypeScript code for calling a 'fetch-weather' tool and a 'display-weather' widget. Assumes a client object is available for tool and widget calls.
```bash
npx create-mcp-use-app my-server --template starter
cd my-server
npm run dev
```
```typescript
// Fetch weather data
const weather = await client.callTool('fetch-weather', { city: 'London' })
// Display it in a beautiful widget
const widget = await client.callTool('display-weather', {
city: 'London',
temperature: '15',
condition: 'Partly Cloudy'
})
```
--------------------------------
### Create and Run a Simple Agent in TypeScript
Source: https://docs.mcp-use.com/typescript/getting-started/quickstart
This snippet shows how to create a basic MCPAgent using a ChatOpenAI LLM and an MCPClient. It then runs a query to find a restaurant and cleans up the client sessions. Requires dotenv for environment variables.
```typescript
import { ChatOpenAI } from '@langchain/openai'
import { config } from 'dotenv'
import { MCPAgent, MCPClient } from 'mcp-use'
async function main() {
// Load environment variables
config()
// Create configuration object
const configuration = {
mcpServers: {
playwright: {
command: 'npx',
args: ['@playwright/mcp@latest'],
env: {
DISPLAY: ':1'
}
}
}
}
// Create MCPClient from configuration object
const client = new MCPClient(configuration)
// Create LLM
const llm = new ChatOpenAI({ model: 'gpt-4o' })
// Create agent with the client
const agent = new MCPAgent({
llm,
client,
maxSteps: 30
})
// Run the query
const result = await agent.run(
'Find the best restaurant in San Francisco USING GOOGLE SEARCH'
)
console.log(`\nResult: ${result}`)
// Clean up
await client.closeAllSessions()
}
main().catch(console.error)
```
--------------------------------
### Reference Environment Variables in Configuration (JSON)
Source: https://docs.mcp-use.com/typescript/advanced/multi-server-setup
This example demonstrates how to reference environment variables defined in a .env file within a JSON configuration. This allows for flexible and secure server setup, such as providing tokens or paths.
```json
{
"mcpServers": {
"github": {
"command": "mcp-server-github",
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}"
}
},
"filesystem": {
"command": "mcp-server-filesystem",
"args": ["${WORKSPACE_PATH}"]
}
}
}
```
--------------------------------
### Input Validation Example for MCP Tool (TypeScript)
Source: https://docs.mcp-use.com/typescript/server/tools
Shows how to implement input validation within an MCP tool's callback function. This example specifically checks for division by zero, returning an error message if the condition is met.
```typescript
server.tool({
name: 'divide',
description: 'Divide two numbers',
inputs: [
{ name: 'dividend', type: 'number', required: true },
{ name: 'divisor', type: 'number', required: true }
],
cb: async ({ dividend, divisor }) => {
// Validation
if (divisor === 0) {
return {
content: [{
type: 'text',
text: 'Error: Division by zero is not allowed'
}]
}
}
const result = dividend / divisor
return {
content: [{
type: 'text',
text: `Result: ${result}`
}]
}
}
})
```
--------------------------------
### Lazy Loading with Server Manager in TypeScript
Source: https://docs.mcp-use.com/typescript/advanced/multi-server-setup
Demonstrates how the server manager enables lazy loading of servers, ensuring they only start when needed. This contrasts with the default behavior where all servers start immediately, leading to potential resource overconsumption. The code shows initialization with and without the server manager.
```typescript
// Without server manager - all servers start immediately
const agent = new MCPAgent({ llm, client, useServerManager: false })
// Result: All 5 servers start, consuming resources
// With server manager - servers start only when needed
const agentOptimized = new MCPAgent({ llm, client, useServerManager: true })
// Result: Only the required servers start for each task
```
```typescript
// Without server manager - all servers start immediately
const agent = new MCPAgent({ llm, client, useServerManager: false })
// Result: All 5 servers start, consuming resources
// With server manager - servers start only when needed
const agentOptimized = new MCPAgent({ llm, client, useServerManager: true })
// Result: Only the required servers start for each task
```
--------------------------------
### Initialize MCP Client and Create Tools with Custom Adapter
Source: https://docs.mcp-use.com/typescript/agent/building-custom-agents
This snippet demonstrates initializing the MCP client with a configuration file and then using a custom adapter to create tools. The adapter abstracts the complexity of tool creation, allowing for a streamlined integration with agent frameworks. Ensure you have 'mcp-use' installed and your custom adapter implementation is correctly imported.
```typescript
import { YourFrameworkAdapter } from './your-module'
import { MCPClient, loadConfigFile } from 'mcp-use'
// Initialize the client
const config = await loadConfigFile('config.json')
const client = new MCPClient(config)
// Create an adapter instance
const adapter = new YourFrameworkAdapter()
// Get tools with a single line
const tools = await adapter.createTools(client)
// Use the tools with your framework
const agent = yourFramework.createAgent({ tools })
```
--------------------------------
### Implement Input Sanitization in TypeScript
Source: https://docs.mcp-use.com/typescript/server/tools
This example demonstrates input sanitization as an error handling best practice. It shows how to validate user input against a list of allowed commands before executing potentially sensitive operations.
```typescript
server.tool({
name: 'execute_command',
description: 'Execute a safe command',
inputs: [
{ name: 'command', type: 'string', required: true }
],
cb: async ({ command }) => {
// Sanitize input
const allowedCommands = ['list', 'status', 'info']
const sanitizedCommand = command.toLowerCase().trim()
if (!allowedCommands.includes(sanitizedCommand)) {
return {
content: [{
type: 'text',
text: `Invalid command. Allowed commands: ${allowedCommands.join(', ')}`
}]
}
}
// Execute safe command
const result = await executeSafeCommand(sanitizedCommand)
return {
content: [{
type: 'text',
text: result
}]
}
}
})
```
--------------------------------
### Define Basic MCP Tool Structure (TypeScript)
Source: https://docs.mcp-use.com/typescript/server/tools
Defines the fundamental structure of an MCP tool, including its name, description, input parameters, and an asynchronous callback handler. This is the starting point for creating any tool.
```typescript
server.tool({
name: 'tool_name', // Unique identifier
description: 'What it does', // Clear description for clients
inputs: [...], // Parameter definitions
cb: async (params) => {...} // Handler function
})
```
--------------------------------
### Call a Tool with Arguments (TypeScript)
Source: https://docs.mcp-use.com/typescript/client/tools
Demonstrates how to instantiate MCPClient, create sessions, and call a specific tool ('read_file') with arguments. It includes basic handling of the tool's result, checking for errors and logging the content. The example assumes pre-configured server definitions in the client's config.
```typescript
import { MCPClient } from 'mcp-use'
async function callToolExample() {
const config = {
mcpServers: {
// Your server definitions here
}
}
const client = new MCPClient(config)
await client.createAllSessions()
const session = client.getSession('filesystem_server')
// Call a tool with arguments
const result = await session.callTool(
'read_file',
{
path: '/path/to/file.txt',
encoding: 'utf-8'
}
)
// Handle the result
if (result.isError) {
console.error(`Error: ${result.content}`)
} else {
console.log(`File content: ${result.content}`)
}
await client.closeAllSessions()
}
callToolExample().catch(console.error)
```
--------------------------------
### Quick Start Apps SDK Template (TypeScript)
Source: https://docs.mcp-use.com/typescript/server/templates
Commands to create an MCP server using the 'apps-sdk' template and showcases TypeScript code for calling the 'display-weather' widget. This template is optimized for OpenAI Apps SDK compatibility.
```bash
npx create-mcp-use-app my-server --template apps-sdk
cd my-server
npm run dev
```
```typescript
// All React components in resources/ folder are automatically registered!
// Just export widgetMetadata and mcp-use handles the rest
const widget = await client.callTool('display-weather', {
city: 'San Francisco',
temperature: '22',
condition: 'Sunny'
})
```
--------------------------------
### Implement Caching for Expensive Operations in TypeScript
Source: https://docs.mcp-use.com/typescript/server/tools
This TypeScript example shows how to implement caching for an expensive operation using mcp-use. It utilizes a Map to store results based on input, avoiding redundant computations and improving performance.
```typescript
const cache = new Map()
server.tool({
name: 'expensive_operation',
description: 'Performs expensive computation',
inputs: [
{ name: 'input', type: 'string', required: true }
],
cb: async ({ input }) => {
// Check cache
const cacheKey = `expensive:${input}`
if (cache.has(cacheKey)) {
return {
content: [{
type: 'text',
text: cache.get(cacheKey)
}]
}
}
// Perform expensive operation
const result = await performExpensiveOperation(input)
// Cache result
cache.set(cacheKey, result)
return {
content: [{
type: 'text',
text: result
}]
}
}
})
```
--------------------------------
### List Available Tools with MCPClient (TypeScript)
Source: https://docs.mcp-use.com/typescript/client/tools
This code snippet demonstrates how to initialize the MCPClient, connect to servers, retrieve a session, and list all available tools. It iterates through the tools, logging their names, descriptions, and input schemas. The function ensures sessions are closed properly afterwards. Dependencies include the 'mcp-use' library.
```typescript
import { MCPClient } from 'mcp-use'
async function listTools() {
// Initialize client with server configuration
const config = {
mcpServers: {
// Your server definitions here
}
}
const client = new MCPClient(config)
// Connect to servers
await client.createAllSessions()
// Get a session for a specific server
const session = client.getSession('my_server')
// List all available tools - always returns fresh data
const tools = await session.listTools()
for (const tool of tools) {
console.log(`Tool: ${tool.name}`)
console.log(`Description: ${tool.description}`)
console.log(`Schema: ${JSON.stringify(tool.inputSchema as any)}`)
console.log('---')
}
await client.closeAllSessions()
}
// Run the example
listTools().catch(console.error)
```
```typescript
import { MCPClient } from 'mcp-use'
async function listTools() {
// Initialize client with server configuration
const config = {
mcpServers: {
// Your server definitions here
}
}
const client = new MCPClient(config)
// Connect to servers
await client.createAllSessions()
// Get a session for a specific server
const session = client.getSession('my_server')
// List all available tools - always returns fresh data
const tools = await session.listTools()
for (const tool of tools) {
console.log(`Tool: ${tool.name}`)
console.log(`Description: ${tool.description}`)
console.log(`Schema: ${JSON.stringify(tool.inputSchema as any)}`)
console.log('---')
}
await client.closeAllSessions()
}
// Run the example
listTools().catch(console.error)
```
--------------------------------
### Async Operations in MCP Tool (TypeScript)
Source: https://docs.mcp-use.com/typescript/server/tools
Illustrates the use of asynchronous operations within an MCP tool's callback function. This example fetches data from an external API, handles potential errors, and returns the data as a JSON string.
```typescript
server.tool({
name: 'fetch_data',
description: 'Fetch data from external API',
inputs: [
{ name: 'endpoint', type: 'string', required: true }
],
cb: async ({ endpoint }) => {
try {
const response = await fetch(endpoint)
const data = await response.json()
return {
content: [{
type: 'text',
text: JSON.stringify(data, null, 2)
}]
}
} catch (error) {
return {
content: [{
type: 'text',
text: `Error fetching data: ${error.message}`
}]
}
}
}
})
```
--------------------------------
### Web Scraping and Data Processing Usage Example (TypeScript)
Source: https://docs.mcp-use.com/typescript/client/multi-server-setup
This TypeScript snippet shows how to use an MCPAgent to scrape product data from a website, process it with Pandas, and save the results. It assumes the necessary MCP servers (Playwright, Pandas, Filesystem) are configured.
```typescript
const result = await agent.run(
'Scrape product data from example-store.com, '
'clean and analyze it with pandas, '
'then save the results as CSV and Excel files'
)
```
--------------------------------
### Start Server Listener (Node.js)
Source: https://docs.mcp-use.com/typescript/server/examples
This code snippet shows how to initiate a server to listen for incoming connections on a specific port. It's a fundamental part of any network application, allowing the server to accept requests. This example uses the standard Node.js `http` module.
```javascript
// Start server
server.listen(3000)
```
--------------------------------
### Add Custom HTTP Routes with Express.js in TypeScript
Source: https://docs.mcp-use.com/typescript/server/getting-started
Integrate custom HTTP routes using Express.js functionality within the MCP server. This allows for creating endpoints like health checks, serving static files, and custom API routes.
```typescript
// Add a health check endpoint
server.get('/health', (req, res) => {
res.json({
status: 'healthy',
timestamp: new Date().toISOString(),
server: 'weather-mcp-server'
})
})
// Serve static files (if you have a public directory)
server.use('/public', express.static('public'))
// Custom API endpoint
server.get('/api/cities', (req, res) => {
res.json(Object.keys(weatherData))
})
```
--------------------------------
### Simplify Tool Creation with MCP-Use Adapter (TypeScript)
Source: https://docs.mcp-use.com/typescript/agent/building-custom-agents
This snippet demonstrates the simplified process of creating LangChain tools directly from an MCP client using the LangChainAdapter. It highlights how the adapter handles session management and initialization, requiring only the creation of an adapter instance and calling its `create_tools` method.
```typescript
const adapter = new LangChainAdapter()
const tools = await adapter.createTools(client)
```
--------------------------------
### Get Prompt Without Arguments using MCPClient in TypeScript
Source: https://docs.mcp-use.com/typescript/client/prompts
Fetches a prompt named 'writing_tips' that does not require any parameters. This example shows the basic usage of `getPrompt` for prompts without arguments, initializing the client, creating a session, retrieving the prompt, and logging its messages. Requires the 'mcp-use' library.
```typescript
async function simplePromptExample() {
const config = {
mcpServers: {
// Your server definitions here
}
}
const client = new MCPClient(config)
await client.createAllSessions()
const session = client.getSession('content_server')
// Get a prompt without arguments
const result = await session.getPrompt('writing_tips')
// Display the prompt content
for (const message of result.messages) {
console.log(`${message.role}: ${message.content.text}`)
}
await client.closeAllSessions()
}
simplePromptExample().catch(console.error)
```
--------------------------------
### Multiple MCP Server Configuration Example
Source: https://docs.mcp-use.com/typescript/client/client-configuration
Illustrates how to configure multiple MCP servers within a single JSON file, demonstrating configurations for 'airbnb', 'playwright', and 'filesystem' servers with their respective settings.
```json
{
"mcpServers": {
"airbnb": {
"command": "npx",
"args": ["-y", "@openbnb/mcp-server-airbnb", "--ignore-robots-txt"]
},
"playwright": {
"command": "npx",
"args": ["@playwright/mcp@latest"],
"env": { "DISPLAY": ":1" }
},
"filesystem": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem",
"/home/pietro/projects/mcp-use/"
]
}
}
}
```
--------------------------------
### Usage Example for Web Scraping Task (TypeScript)
Source: https://docs.mcp-use.com/typescript/advanced/multi-server-setup
This TypeScript code snippet shows how to use an MCP agent to perform a complex task involving web scraping, data analysis with pandas, and saving results to files. It assumes the agent is configured with the necessary servers, such as Playwright, Pandas, and a filesystem server.
```typescript
const result = await agent.run(
'Scrape product data from example-store.com, '
)
```
--------------------------------
### Configure LLM Provider API Keys
Source: https://docs.mcp-use.com/typescript/getting-started/quickstart
Sets environment variables for various LLM providers, such as OpenAI, Anthropic, Groq, and Google. This is crucial for secure API key management when using mcp-use with different language models.
```dotenv
# LLM Provider Keys (set the ones you want to use)
OPENAI_API_KEY=your_api_key_here
ANTHROPIC_API_KEY=your_api_key_here
GROQ_API_KEY=your_api_key_here
GOOGLE_API_KEY=your_api_key_here
```