Skip to content
This repository was archived by the owner on May 21, 2026. It is now read-only.

Commit d88df37

Browse files
committed
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
1 parent f2799fb commit d88df37

7 files changed

Lines changed: 586 additions & 22 deletions

File tree

README.md

Lines changed: 209 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,214 @@ export function Chat() {
295296

296297
---
297298

299+
## 📊 Observability & Monitoring
300+
301+
mcp-use-ts provides built-in observability support through the `ObservabilityManager`, with seamless integration for Langfuse and other observability platforms.
302+
303+
### Features
304+
305+
- **Automatic Tracing**: All agent executions, tool calls, and LLM interactions are automatically traced
306+
- **Dynamic Metadata**: Add contextual metadata to traces at runtime
307+
- **Tag Support**: Tag traces with dynamic information for better organization
308+
- **Langfuse Integration**: Native support for Langfuse observability platform
309+
- **Custom Callbacks**: Support for additional custom callback handlers
310+
311+
### Setup
312+
313+
#### 1. Install Observability Dependencies
314+
315+
```bash
316+
npm install langfuse langfuse-langchain
317+
```
318+
319+
#### 2. Configure Environment Variables
320+
321+
```ini
322+
# .env
323+
LANGFUSE_PUBLIC_KEY=pk-lf-your-public-key
324+
LANGFUSE_SECRET_KEY=sk-lf-your-secret-key
325+
LANGFUSE_HOST=https://cloud.langfuse.com # or your self-hosted instance
326+
```
327+
328+
#### 3. Basic Usage
329+
330+
```ts
331+
import { MCPAgent, MCPClient, ObservabilityManager } from 'mcp-use'
332+
import { ChatOpenAI } from '@langchain/openai'
333+
334+
const client = new MCPClient({
335+
mcpServers: {
336+
everything: { command: 'npx', args: ['-y', '@modelcontextprotocol/server-everything'] }
337+
}
338+
})
339+
340+
const llm = new ChatOpenAI({ model: 'gpt-4o' })
341+
342+
// Create agent with observability enabled
343+
const agent = new MCPAgent({
344+
llm,
345+
client,
346+
maxSteps: 10,
347+
verbose: true // Enable verbose logging for better observability
348+
})
349+
350+
// Initialize to set up observability callbacks
351+
await agent.initialize()
352+
353+
// Run queries - all interactions will be automatically traced
354+
const result = await agent.run('What tools are available?')
355+
```
356+
357+
### Advanced Observability Features
358+
359+
#### Dynamic Metadata and Tags
360+
361+
```ts
362+
// Set metadata for the current execution
363+
agent.setMetadata({
364+
userId: 'user123',
365+
sessionId: 'session456',
366+
environment: 'production'
367+
})
368+
369+
// Set tags for better organization
370+
agent.setTags(['production', 'user-query', 'tool-discovery'])
371+
372+
// Run query with metadata and tags
373+
const result = await agent.run('Search for restaurants in Tokyo')
374+
```
375+
376+
#### Custom Observability Manager
377+
378+
```ts
379+
import { ObservabilityManager } from 'mcp-use'
380+
381+
// Create custom observability manager
382+
const observabilityManager = new ObservabilityManager({
383+
verbose: true,
384+
agentId: 'my-custom-agent',
385+
metadata: {
386+
version: '1.0.0',
387+
deployment: 'production'
388+
},
389+
metadataProvider: () => ({
390+
timestamp: new Date().toISOString(),
391+
requestId: crypto.randomUUID()
392+
}),
393+
tagsProvider: () => ['automated', 'scheduled']
394+
})
395+
396+
// Use with MCPAgent
397+
const agent = new MCPAgent({
398+
llm,
399+
client,
400+
callbacks: await observabilityManager.getCallbacks()
401+
})
402+
```
403+
404+
#### Runtime Metadata Updates
405+
406+
```ts
407+
// Update metadata during execution
408+
agent.setMetadata({
409+
currentStep: 1,
410+
toolsUsed: ['search', 'browse']
411+
})
412+
413+
// Add more tags
414+
agent.setTags(['step-1', 'search-complete'])
415+
416+
// Continue execution with updated context
417+
const result = await agent.run('Continue with the search')
418+
```
419+
420+
### Observability in Production
421+
422+
#### Environment Configuration
423+
424+
```ts
425+
// Production setup with comprehensive observability
426+
const agent = new MCPAgent({
427+
llm,
428+
client,
429+
maxSteps: 20,
430+
verbose: process.env.NODE_ENV === 'development',
431+
// Observability is automatically enabled when environment variables are set
432+
})
433+
434+
await agent.initialize()
435+
436+
// Set production metadata
437+
agent.setMetadata({
438+
service: 'mcp-agent',
439+
version: process.env.APP_VERSION,
440+
environment: process.env.NODE_ENV,
441+
region: process.env.AWS_REGION
442+
})
443+
444+
agent.setTags(['production', 'api', 'mcp-agent'])
445+
```
446+
447+
#### Monitoring Agent Performance
448+
449+
```ts
450+
// Stream events for detailed monitoring
451+
const eventStream = agent.streamEvents('Complex multi-step query')
452+
453+
for await (const event of eventStream) {
454+
// Monitor different event types
455+
switch (event.event) {
456+
case 'on_llm_start':
457+
console.log('LLM call started:', event.data)
458+
break
459+
case 'on_tool_start':
460+
console.log('Tool execution started:', event.name, event.data)
461+
break
462+
case 'on_tool_end':
463+
console.log('Tool execution completed:', event.name, event.data)
464+
break
465+
case 'on_chain_end':
466+
console.log('Agent execution completed:', event.data)
467+
break
468+
}
469+
}
470+
```
471+
472+
### Disabling Observability
473+
474+
To disable observability, set the environment variable:
475+
476+
```ini
477+
MCP_USE_LANGFUSE=false
478+
```
479+
480+
Or programmatically:
481+
482+
```ts
483+
const agent = new MCPAgent({
484+
llm,
485+
client,
486+
callbacks: [] // No callbacks = no observability
487+
})
488+
```
489+
490+
### Available Observability Exports
491+
492+
```ts
493+
import {
494+
ObservabilityManager,
495+
type ObservabilityConfig
496+
} from 'mcp-use'
497+
498+
// Use ObservabilityManager directly for custom setups
499+
const manager = new ObservabilityManager({
500+
verbose: true,
501+
agentId: 'custom-agent'
502+
})
503+
```
504+
505+
---
506+
298507
## 📂 Configuration File
299508

300509
You can store servers in a JSON file:

examples/mcp_everything.ts

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,28 +5,57 @@
55

66
import { ChatOpenAI } from '@langchain/openai'
77
import { config } from 'dotenv'
8-
import { MCPAgent, MCPClient } from '../index.js'
8+
import { Logger, MCPAgent, MCPClient } from '../index.js'
99

1010
// Load environment variables from .env file
1111
config()
1212

13+
// Enable debug logging to see observability messages
14+
Logger.setDebug(true)
15+
1316
const everythingServer = {
1417
mcpServers: { everything: { command: 'npx', args: ['-y', '@modelcontextprotocol/server-everything'] } },
1518
}
1619

1720
async function main() {
21+
console.log('🚀 Starting MCP Everything 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+
1828
const client = new MCPClient(everythingServer)
1929
const llm = new ChatOpenAI({ model: 'gpt-4o', temperature: 0 })
20-
const agent = new MCPAgent({ llm, client, maxSteps: 30 })
30+
const agent = new MCPAgent({
31+
llm,
32+
client,
33+
maxSteps: 30,
34+
})
35+
36+
console.log('🔧 Initializing agent...')
37+
await agent.initialize()
2138

39+
// Set additional metadata for testing
40+
agent.setMetadata({
41+
agent_id: 'test-agent-123',
42+
test_run: true,
43+
example: 'mcp_everything',
44+
})
45+
46+
console.log('💬 Running agent query...')
2247
const result = await agent.run(
2348
`Hello, you are a tester can you please answer the follwing questions:
2449
- Which resources do you have access to?
2550
- Which prompts do you have access to?
2651
- Which tools do you have access to?`,
2752
30,
2853
)
29-
console.log(`\nResult: ${result}`)
54+
console.log(`\n✅ Result: ${result}`)
55+
56+
console.log('🧹 Closing agent...')
57+
await agent.close()
58+
console.log('🎉 Example completed! Check your Langfuse dashboard for traces.')
3059
}
3160

3261
if (import.meta.url === `file://${process.argv[1]}`) {

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

0 commit comments

Comments
 (0)