Skip to content

Commit efa36d5

Browse files
committed
Add examples
1 parent cf63874 commit efa36d5

13 files changed

+733
-5
lines changed

README.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,38 @@ const client = MCPClient.fromConfigFile('./mcp-config.json')
126126

127127
---
128128

129+
## 📚 Examples
130+
131+
We provide a comprehensive set of examples demonstrating various use cases. All examples are located in the `examples/` directory with a dedicated README.
132+
133+
### Running Examples
134+
135+
```bash
136+
# Install dependencies
137+
npm install
138+
139+
# Run any example
140+
npm run example:airbnb # Search accommodations with Airbnb
141+
npm run example:browser # Browser automation with Playwright
142+
npm run example:chat # Interactive chat with memory
143+
npm run example:filesystem # File system operations
144+
npm run example:http # HTTP server connection
145+
npm run example:everything # Test MCP functionalities
146+
npm run example:multi # Multiple servers in one session
147+
```
148+
149+
### Example Highlights
150+
151+
- **Browser Automation**: Control browsers to navigate websites and extract information
152+
- **File Operations**: Read, write, and manipulate files through MCP
153+
- **Multi-Server**: Combine multiple MCP servers (Airbnb + Browser) in a single task
154+
- **Sandboxed Execution**: Run MCP servers in isolated E2B containers
155+
- **OAuth Flows**: Authenticate with services like Linear using OAuth2
156+
157+
See the [examples README](./examples/README.md) for detailed documentation and prerequisites.
158+
159+
---
160+
129161
## 🔄 Multi-Server Example
130162

131163
```ts

eslint.config.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,9 @@ export default antfu({
66
rules: {
77
'node/prefer-global/process': 'off',
88
},
9+
}, {
10+
files: ['examples/**/*.ts'],
11+
rules: {
12+
'no-console': 'off',
13+
},
914
})

examples/README.md

Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
# MCP-Use TypeScript Examples
2+
3+
This directory contains examples demonstrating how to use the mcp-use library with various MCP servers.
4+
5+
## Prerequisites
6+
7+
1. **Node.js**: Ensure you have Node.js 22+ installed
8+
2. **Environment Variables**: Create a `.env` file in the project root with your API keys:
9+
```bash
10+
ANTHROPIC_API_KEY=your_anthropic_key
11+
OPENAI_API_KEY=your_openai_key
12+
E2B_API_KEY=your_e2b_key # Only for sandbox example
13+
```
14+
15+
## Running Examples
16+
17+
First, build the library:
18+
```bash
19+
npm run build
20+
```
21+
22+
Then run any example using Node.js:
23+
```bash
24+
node dist/examples/example_name.js
25+
```
26+
27+
Or use the npm scripts:
28+
```bash
29+
npm run example:airbnb
30+
npm run example:browser
31+
npm run example:chat
32+
# ... etc
33+
```
34+
35+
## Available Examples
36+
37+
### 1. Airbnb Search (`airbnb_use.ts`)
38+
Search for accommodations using the Airbnb MCP server.
39+
```bash
40+
npm run example:airbnb
41+
```
42+
43+
### 2. Browser Automation (`browser_use.ts`)
44+
Control a browser using Playwright MCP server.
45+
```bash
46+
npm run example:browser
47+
```
48+
49+
### 3. Interactive Chat (`chat_example.ts`)
50+
Interactive chat session with conversation memory.
51+
```bash
52+
npm run example:chat
53+
```
54+
55+
### 4. File System Operations (`filesystem_use.ts`)
56+
Access and manipulate files using the filesystem MCP server.
57+
```bash
58+
# First, edit the example to set your directory path
59+
npm run example:filesystem
60+
```
61+
62+
### 5. HTTP Server Connection (`http_example.ts`)
63+
Connect to an MCP server via HTTP.
64+
```bash
65+
# First, start the Playwright server in another terminal:
66+
npx @playwright/mcp@latest --port 8931
67+
68+
# Then run the example:
69+
npm run example:http
70+
```
71+
72+
### 6. MCP Everything Test (`mcp_everything.ts`)
73+
Test various MCP functionalities.
74+
```bash
75+
npm run example:everything
76+
```
77+
78+
### 7. Multiple Servers (`multi_server_example.ts`)
79+
Use multiple MCP servers in a single session.
80+
```bash
81+
# First, edit the example to set your directory path
82+
npm run example:multi
83+
```
84+
85+
### 8. Sandboxed Environment (`sandbox_everything.ts`)
86+
Run MCP servers in an E2B sandbox (requires E2B_API_KEY).
87+
```bash
88+
npm run example:sandbox
89+
```
90+
91+
### 9. OAuth Authentication (`simple_oauth_example.ts`)
92+
OAuth flow example with Linear.
93+
```bash
94+
# First, register your app with Linear and update the client_id
95+
npm run example:oauth
96+
```
97+
98+
### 10. Blender Integration (`blender_use.ts`)
99+
Control Blender 3D through MCP.
100+
```bash
101+
# First, install and enable the Blender MCP addon
102+
npm run example:blender
103+
```
104+
105+
## Configuration Files
106+
107+
Some examples use JSON configuration files:
108+
- `airbnb_mcp.json` - Airbnb server configuration
109+
- `browser_mcp.json` - Browser server configuration
110+
111+
## Environment Variables
112+
113+
Different examples require different API keys:
114+
- **ANTHROPIC_API_KEY**: For examples using Claude (airbnb, multi_server, blender)
115+
- **OPENAI_API_KEY**: For examples using GPT (browser, chat, filesystem, http, everything)
116+
- **E2B_API_KEY**: Only for the sandbox example
117+
118+
## Troubleshooting
119+
120+
1. **Module not found**: Make sure to build the project first with `npm run build`
121+
2. **API key errors**: Check your `.env` file has the required keys
122+
3. **Server connection failed**: Some examples require external servers to be running
123+
4. **Permission errors**: Some examples may need specific permissions (e.g., filesystem access)
124+
125+
## Writing Your Own Examples
126+
127+
To create a new example:
128+
129+
1. Import the necessary modules:
130+
```typescript
131+
import { MCPAgent, MCPClient } from '../index.js'
132+
import { ChatOpenAI } from '@langchain/openai'
133+
```
134+
135+
2. Configure your MCP server:
136+
```typescript
137+
const config = {
138+
mcpServers: {
139+
yourServer: {
140+
command: 'npx',
141+
args: ['your-mcp-server']
142+
}
143+
}
144+
}
145+
```
146+
147+
3. Create client, LLM, and agent:
148+
```typescript
149+
const client = MCPClient.fromDict(config)
150+
const llm = new ChatOpenAI({ model: 'gpt-4o' })
151+
const agent = new MCPAgent({ llm, client, maxSteps: 30 })
152+
```
153+
154+
4. Run your queries:
155+
```typescript
156+
const result = await agent.run('Your prompt here', { maxSteps: 30 })
157+
```
158+
159+
## Contributing
160+
161+
Feel free to add more examples! Make sure to:
162+
1. Follow the existing code style
163+
2. Add appropriate documentation
164+
3. Update this README with your example
165+
4. Add a corresponding npm script in package.json

examples/airbnb_use.ts

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* Example demonstrating how to use mcp-use with Airbnb.
3+
*
4+
* This example shows how to connect an LLM to Airbnb through MCP tools
5+
* to perform tasks like searching for accommodations.
6+
*
7+
* Special Thanks to https://github.com/openbnb-org/mcp-server-airbnb for the server.
8+
*/
9+
10+
import { ChatOpenAI } from '@langchain/openai'
11+
import { config } from 'dotenv'
12+
import { MCPAgent, MCPClient } from '../index.js'
13+
14+
// Load environment variables from .env file
15+
config()
16+
17+
async function runAirbnbExample() {
18+
// Create MCPClient with Airbnb configuration
19+
const config = {
20+
mcpServers: {
21+
airbnb: {
22+
command: 'npx',
23+
args: ['-y', '@openbnb/mcp-server-airbnb', '--ignore-robots-txt'],
24+
},
25+
},
26+
}
27+
const client = new MCPClient(config)
28+
// Create LLM - you can choose between different models
29+
const llm = new ChatOpenAI({ model: 'gpt-4o' })
30+
31+
// Create agent with the client
32+
const agent = new MCPAgent({ llm, client, maxSteps: 30 })
33+
34+
try {
35+
// Run a query to search for accommodations
36+
const result = await agent.run(
37+
'Find me a nice place to stay in Barcelona for 2 adults '
38+
+ 'for a week in August. I prefer places with a pool and '
39+
+ 'good reviews. Show me the top 3 options.',
40+
30,
41+
)
42+
console.error(`\nResult: ${result}`)
43+
}
44+
finally {
45+
// Ensure we clean up resources properly
46+
await client.closeAllSessions()
47+
}
48+
}
49+
50+
if (import.meta.url === `file://${process.argv[1]}`) {
51+
runAirbnbExample().catch(console.error)
52+
}

examples/blender_use.ts

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* Blender MCP example for mcp-use.
3+
*
4+
* This example demonstrates how to use the mcp-use library with MCPClient
5+
* to connect an LLM to Blender through MCP tools via WebSocket.
6+
* The example assumes you have installed the Blender MCP addon from:
7+
* https://github.com/ahujasid/blender-mcp
8+
*
9+
* Make sure the addon is enabled in Blender preferences and the WebSocket
10+
* server is running before executing this script.
11+
*
12+
* Special thanks to https://github.com/ahujasid/blender-mcp for the server.
13+
*/
14+
15+
import { ChatAnthropic } from '@langchain/anthropic'
16+
import { config } from 'dotenv'
17+
import { MCPAgent, MCPClient } from '../index.js'
18+
19+
// Load environment variables from .env file
20+
config()
21+
22+
async function runBlenderExample() {
23+
// Create MCPClient with Blender MCP configuration
24+
const config = { mcpServers: { blender: { command: 'uvx', args: ['blender-mcp'] } } }
25+
const client = MCPClient.fromDict(config)
26+
27+
// Create LLM
28+
const llm = new ChatAnthropic({ model: 'claude-3-5-sonnet-20240620' })
29+
30+
// Create agent with the client
31+
const agent = new MCPAgent({ llm, client, maxSteps: 30 })
32+
33+
try {
34+
// Run the query
35+
const result = await agent.run(
36+
'Create an inflatable cube with soft material and a plane as ground.',
37+
30,
38+
)
39+
console.error(`\nResult: ${result}`)
40+
}
41+
finally {
42+
// Ensure we clean up resources properly
43+
await client.closeAllSessions()
44+
}
45+
}
46+
47+
if (import.meta.url === `file://${process.argv[1]}`) {
48+
runBlenderExample().catch(console.error)
49+
}

examples/browser_use.ts

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/**
2+
* Basic usage example for mcp-use.
3+
*
4+
* This example demonstrates how to use the mcp-use library with MCPClient
5+
* to connect any LLM to MCP tools through a unified interface.
6+
*
7+
* Special thanks to https://github.com/microsoft/playwright-mcp for the server.
8+
*/
9+
10+
import path from 'node:path'
11+
import { fileURLToPath } from 'node:url'
12+
import { ChatOpenAI } from '@langchain/openai'
13+
import { config } from 'dotenv'
14+
import { MCPAgent, MCPClient } from '../index.js'
15+
16+
// Load environment variables from .env file
17+
config()
18+
19+
const __filename = fileURLToPath(import.meta.url)
20+
const __dirname = path.dirname(__filename)
21+
22+
async function main() {
23+
const config = {
24+
mcpServers: {
25+
playwright: {
26+
command: 'npx',
27+
args: ['@playwright/mcp@latest'],
28+
env: {
29+
DISPLAY: ':1',
30+
},
31+
},
32+
},
33+
}
34+
// Create MCPClient from config file
35+
const client = new MCPClient(config)
36+
37+
// Create LLM
38+
const llm = new ChatOpenAI({ model: 'gpt-4o' })
39+
// const llm = init_chat_model({ model: "llama-3.1-8b-instant", model_provider: "groq" })
40+
// const llm = new ChatAnthropic({ model: "claude-3-" })
41+
// const llm = new ChatGroq({ model: "llama3-8b-8192" })
42+
43+
// Create agent with the client
44+
const agent = new MCPAgent({ llm, client, maxSteps: 30 })
45+
46+
// Run the query
47+
const result = await agent.run(
48+
`Navigate to https://github.com/mcp-use/mcp-use, give a star to the project and write
49+
a summary of the project.`,
50+
30,
51+
)
52+
console.error(`\nResult: ${result}`)
53+
}
54+
55+
if (import.meta.url === `file://${process.argv[1]}`) {
56+
main().catch(console.error)
57+
}

0 commit comments

Comments
 (0)