Skip to content

Commit 8dc449d

Browse files
authored
feat: enhance observability with improved metadata and tag handling (#49)
* feat: enhance observability with improved metadata and tag handling - Add ObservabilityManager export to main index.ts for better accessibility - Refactor MCPAgent to support dynamic metadata and tag providers - Enhance Langfuse integration with custom metadata and tag support - Improve observability manager with better initialization and callback handling - Update examples and tests to reflect new observability features - Add support for runtime metadata and tag updates during agent execution - Add comprehensive observability documentation to README with setup guides, usage examples, and production configuration instructions - Fix linting errors in README and DEVELOPMENT.md - Add markdown files to pre-commit hook for consistent code quality * pnpm update * remove lint * feat: add observability example and enhance README documentation - Introduced a new example for observability integration in mcp_everything.ts - Updated README to streamline observability setup instructions and remove redundant sections - Added support for an 'observe' option in MCPAgent and ObservabilityManager to control observability behavior - Improved observability manager to handle cases when observability is disabled - Cleaned up example code for better clarity and removed unnecessary debug logging
1 parent f2799fb commit 8dc449d

File tree

10 files changed

+1855
-1596
lines changed

10 files changed

+1855
-1596
lines changed

DEVELOPMENT.md

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -5,26 +5,19 @@ This document provides guidance for developers contributing to this project and
55
## Setting Up Development Environment
66

77
1. Clone the repository:
8-
98
```bash
109
git clone https://github.com/zandko/mcp-use.git
1110
cd mcp-use
1211
```
13-
1412
2. Install dependencies:
15-
1613
```bash
1714
pnpm install
1815
```
19-
2016
> **Note**: This project requires Node.js version 22 or higher.
21-
2217
3. Build the project:
23-
2418
```bash
2519
pnpm build
2620
```
27-
2821
4. Watch for changes during development:
2922
```bash
3023
pnpm watch
@@ -62,33 +55,25 @@ We use GitHub Actions to automate our release process, connecting GitHub Release
6255
#### For Maintainers
6356

6457
1. **Prepare for Release**:
65-
6658
Update the version in `package.json` using one of these commands:
67-
6859
```bash
6960
# For patch releases (0.0.x) - Bug fixes
7061
pnpm run release
71-
7262
# For minor releases (0.x.0) - New features
7363
pnpm run release:minor
74-
7564
# For major releases (x.0.0) - Breaking changes
7665
pnpm run release:major
7766
```
78-
7967
This will:
8068
- Update the version in package.json
8169
- Create a git tag
8270
- Push the changes and tag to GitHub
83-
8471
2. **Create GitHub Release**:
8572
- Go to GitHub repository → "Releases" → "Draft a new release"
8673
- Choose the tag that was just created
8774
- Fill in release notes detailing what's new, fixes, and any breaking changes
8875
- Click "Publish release"
89-
9076
3. **Automated Publishing**:
91-
9277
The GitHub Action will automatically:
9378
- Verify the package version matches the GitHub tag
9479
- Run linting and build checks
@@ -105,11 +90,9 @@ To set up automated publishing:
10590
1. Generate an NPM access token:
10691
- Go to npmjs.com → User Settings → Access Tokens
10792
- Create a new token with "Automation" type and publish permissions
108-
10993
2. Add the token to GitHub repository secrets:
11094
- Go to your GitHub repository → Settings → Secrets → Actions
11195
- Add a new secret named `NPM_TOKEN` with the value of your NPM token
112-
11396
3. (Optional) Discord notifications:
11497
- Create a Discord webhook in your server
11598
- Add the webhook URL as a GitHub repository secret named `DISCORD_WEBHOOK`

README.md

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
| 🧩 **Multi-Server Support** | Use multiple MCP servers in one agent. |
4545
| 🛡️ **Tool Restrictions** | Restrict unsafe tools like filesystem or network. |
4646
| 🔧 **Custom Agents** | Build your own agents with LangChain.js adapter or implement new adapters. |
47+
| 📊 **Observability** | Built-in support for Langfuse with dynamic metadata and tag handling. |
4748

4849
---
4950

@@ -295,6 +296,77 @@ export function Chat() {
295296

296297
---
297298

299+
## 📊 Observability & Monitoring
300+
301+
mcp-use-ts provides built-in observability support through the `ObservabilityManager`, with integration for Langfuse and other observability platforms.
302+
303+
#### To enable observability simply configure Environment Variables
304+
305+
```ini
306+
# .env
307+
LANGFUSE_PUBLIC_KEY=pk-lf-your-public-key
308+
LANGFUSE_SECRET_KEY=sk-lf-your-secret-key
309+
LANGFUSE_HOST=https://cloud.langfuse.com # or your self-hosted instance
310+
```
311+
312+
### Advanced Observability Features
313+
314+
#### Dynamic Metadata and Tags
315+
316+
```ts
317+
// Set custom metadata for the current execution
318+
agent.setMetadata({
319+
userId: 'user123',
320+
sessionId: 'session456',
321+
environment: 'production'
322+
})
323+
324+
// Set tags for better organization
325+
agent.setTags(['production', 'user-query', 'tool-discovery'])
326+
327+
// Run query with metadata and tags
328+
const result = await agent.run('Search for restaurants in Tokyo')
329+
```
330+
331+
#### Monitoring Agent Performance
332+
333+
```ts
334+
// Stream events for detailed monitoring
335+
const eventStream = agent.streamEvents('Complex multi-step query')
336+
337+
for await (const event of eventStream) {
338+
// Monitor different event types
339+
switch (event.event) {
340+
case 'on_llm_start':
341+
console.log('LLM call started:', event.data)
342+
break
343+
case 'on_tool_start':
344+
console.log('Tool execution started:', event.name, event.data)
345+
break
346+
case 'on_tool_end':
347+
console.log('Tool execution completed:', event.name, event.data)
348+
break
349+
case 'on_chain_end':
350+
console.log('Agent execution completed:', event.data)
351+
break
352+
}
353+
}
354+
```
355+
356+
### Disabling Observability
357+
358+
To disable observability, either remove langfuse env variables or
359+
360+
```ts
361+
const agent = new MCPAgent({
362+
llm,
363+
client,
364+
observe: false
365+
})
366+
```
367+
368+
---
369+
298370
## 📂 Configuration File
299371

300372
You can store servers in a JSON file:

examples/observability.ts

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/**
2+
* This example shows how to test the different functionalities of MCPs using the MCP server from
3+
* anthropic.
4+
*/
5+
6+
import { ChatOpenAI } from '@langchain/openai'
7+
import { config } from 'dotenv'
8+
import { Logger, MCPAgent, MCPClient } from '../index.js'
9+
10+
// Load environment variables from .env file
11+
config()
12+
13+
// Enable debug logging to see observability messages
14+
Logger.setDebug(true)
15+
16+
const everythingServer = {
17+
mcpServers: { everything: { command: 'npx', args: ['-y', '@modelcontextprotocol/server-everything'] } },
18+
}
19+
20+
async function main() {
21+
console.log('🚀 Starting MCP Observability example with Langfuse tracing...')
22+
console.log('📊 Environment variables:')
23+
console.log(` LANGFUSE_PUBLIC_KEY: ${process.env.LANGFUSE_PUBLIC_KEY ? '✅ Set' : '❌ Missing'}`)
24+
console.log(` LANGFUSE_SECRET_KEY: ${process.env.LANGFUSE_SECRET_KEY ? '✅ Set' : '❌ Missing'}`)
25+
console.log(` LANGFUSE_HOST: ${process.env.LANGFUSE_HOST || 'Not set'}`)
26+
console.log(` MCP_USE_LANGFUSE: ${process.env.MCP_USE_LANGFUSE || 'Not set'}`)
27+
28+
const client = new MCPClient(everythingServer)
29+
const llm = new ChatOpenAI({ model: 'gpt-4o', temperature: 0 })
30+
const agent = new MCPAgent({
31+
llm,
32+
client,
33+
maxSteps: 30,
34+
})
35+
36+
// console.log('🔧 Initializing agent...')
37+
// await agent.initialize()
38+
39+
// Set additional metadata for testing (Optional)
40+
agent.setMetadata({
41+
agent_id: 'test-agent-123',
42+
test_run: true,
43+
example: 'mcp_observability',
44+
})
45+
46+
agent.setTags(['test-tag-1', 'test-tag-2'])
47+
48+
console.log('💬 Running agent query...')
49+
const result = await agent.run(
50+
`Hello, you are a tester can you please answer the follwing questions:
51+
- Which resources do you have access to?
52+
- Which prompts do you have access to?
53+
- Which tools do you have access to?`,
54+
30,
55+
)
56+
console.log(`\n✅ Result: ${result}`)
57+
58+
// console.log('🧹 Closing agent...')
59+
// await agent.close()
60+
// console.log('🎉 Example completed! Check your Langfuse dashboard for traces.')
61+
}
62+
63+
if (import.meta.url === `file://${process.argv[1]}`) {
64+
main().catch(console.error)
65+
}

index.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@ export { ServerManager } from './src/managers/server_manager.js'
1717

1818
export * from './src/managers/tools/index.js'
1919

20+
// Export observability utilities
21+
export { type ObservabilityConfig, ObservabilityManager } from './src/observability/index.js'
22+
2023
// Export telemetry utilities
2124
export { setTelemetrySource, Telemetry } from './src/telemetry/index.js'
2225

package.json

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,8 @@
7474
"example:oauth": "npm run build && node dist/examples/simple_oauth_example.js",
7575
"example:blender": "npm run build && node dist/examples/blender_use.js",
7676
"example:add_server": "npm run build && node dist/examples/add_server_tool.js",
77-
"example:structured": "npm run build && node dist/examples/structured_output.js"
77+
"example:structured": "npm run build && node dist/examples/structured_output.js",
78+
"example:observability": "npm run build && node dist/examples/observability.js"
7879
},
7980
"peerDependencies": {
8081
"langfuse": "^3.32.0",
@@ -122,6 +123,10 @@
122123
"*.{js,ts}": [
123124
"eslint --fix",
124125
"eslint"
126+
],
127+
"*.md": [
128+
"eslint --fix",
129+
"eslint"
125130
]
126131
}
127132
}

0 commit comments

Comments
 (0)