Skip to content

Commit 7762f2d

Browse files
iOSDevSKclaude
andcommitted
feat: Add token counting system and various improvements
- Enhanced MCP client with token counting capabilities - Added comprehensive test files and examples - Updated documentation and project configuration - Improved connector implementations - Added elicitation functionality - Removed sensitive JWT token from CLAUDE.md 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
1 parent e90f590 commit 7762f2d

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

58 files changed

+18160
-55
lines changed

CLAUDE.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# CLAUDE.md
22

3+
34
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
45

56
## Project Overview

CONTRIBUTING.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ MCP-Use requires:
3939
```
4040
3. Install the package in development mode:
4141
```bash
42-
pip install -e ".[dev,search,e2b]"
42+
pip install -e ".[dev,search]"
4343
```
4444
4. Set up pre-commit hooks:
4545
```bash

README.md

Lines changed: 17 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
<div align="center">
21
<div align="center" style="margin: 0 auto; max-width: 80%;">
32
<picture>
43
<source media="(prefers-color-scheme: dark)" srcset="static/logo_white.svg">
@@ -7,23 +6,24 @@
76
</picture>
87
</div>
98

10-
<br>
11-
12-
# Connect any LLM to any MCP server
13-
9+
<h1 align="center">Unified MCP Client Library </h1>
1410
<p align="center">
15-
<a href="https://github.com/pietrozullo/mcp-use/stargazers" alt="GitHub stars">
16-
<img src="https://img.shields.io/github/stars/pietrozullo/mcp-use?style=social" /></a>
1711
<a href="https://pypi.org/project/mcp_use/" alt="PyPI Version">
1812
<img src="https://img.shields.io/pypi/v/mcp_use.svg"/></a>
19-
<a href="https://github.com/pietrozullo/mcp-use/blob/main/LICENSE" alt="License">
20-
<img src="https://img.shields.io/github/license/pietrozullo/mcp-use" /></a>
2113
<a href="https://pypi.org/project/mcp_use/" alt="PyPI Downloads">
2214
<img src="https://static.pepy.tech/badge/mcp-use" /></a>
15+
<a href="https://pypi.org/project/mcp_use/" alt="Python Versions">
16+
<img src="https://img.shields.io/pypi/pyversions/mcp_use.svg" /></a>
2317
<a href="https://docs.mcp-use.com" alt="Documentation">
24-
<img src="https://img.shields.io/badge/docs-mcp--use.com-blue" /></a>
18+
<img src="https://img.shields.io/badge/docs-mcp--use.io-blue" /></a>
2519
<a href="https://mcp-use.com" alt="Website">
26-
<img src="https://img.shields.io/badge/website-mcp--use.com-blue" /></a>
20+
<img src="https://img.shields.io/badge/website-mcp--use.io-blue" /></a>
21+
<a href="https://github.com/pietrozullo/mcp-use/blob/main/LICENSE" alt="License">
22+
<img src="https://img.shields.io/github/license/pietrozullo/mcp-use" /></a>
23+
<a href="https://github.com/astral-sh/ruff" alt="Code style: Ruff">
24+
<img src="https://img.shields.io/badge/code%20style-ruff-000000.svg" /></a>
25+
<a href="https://github.com/pietrozullo/mcp-use/stargazers" alt="GitHub stars">
26+
<img src="https://img.shields.io/github/stars/pietrozullo/mcp-use?style=social" /></a>
2727
</p>
2828
<p align="center">
2929
<a href="https://x.com/pietrozullo" alt="Twitter Follow - Pietro">
@@ -33,24 +33,15 @@
3333
<a href="https://discord.gg/XkNkSkMz3V" alt="Discord">
3434
<img src="https://dcbadge.limes.pink/api/server/XkNkSkMz3V?style=flat" /></a>
3535
</p>
36-
</div>
36+
🌐 MCP-Use is the open source way to connect **any LLM to any MCP server** and build custom agents that have tool access, without using closed source or application clients.
3737

38-
🌐 MCP-Use is the open source way to connect **any LLM to any MCP server** and build custom MCP agents that have tool access, without using closed source or application clients.
38+
💬 Get started quickly - chat with your servers on our <b>hosted version</b>! <b>[Try mcp-use chat *(beta)* ](https://chat.mcp-use.com)</b>.
3939

4040
💡 Let developers easily connect any LLM to tools like web browsing, file operations, and more.
4141

42-
- Visit the [mcp-use.com website](https://mcp-use.com/) to know how to build and deploy MCP agents.
43-
- Visit the [mcp-use docs](https://docs.mcp-use.com/) to get started with mcp-use library
44-
45-
💬 Get started quickly - chat with your servers on our <b>hosted version</b>! [Try mcp-use chat (beta)](https://chat.mcp-use.com).
46-
47-
| Supports | |
48-
| :--- | :--- |
49-
| **Primitives** | [![Tools](https://img.shields.io/github/actions/workflow/status/pietrozullo/mcp-use/testprimitives.yml?job=tools&label=Tools&style=flat)](https://github.com/pietrozullo/mcp-use/actions/workflows/testprimitives.yml) [![Resources](https://img.shields.io/github/actions/workflow/status/pietrozullo/mcp-use/testprimitives.yml?job=resources&label=Resources&style=flat)](https://github.com/pietrozullo/mcp-use/actions/workflows/testprimitives.yml) [![Prompts](https://img.shields.io/github/actions/workflow/status/pietrozullo/mcp-use/testprimitives.yml?job=prompts&label=Prompts&style=flat)](https://github.com/pietrozullo/mcp-use/actions/workflows/testprimitives.yml) [![Sampling](https://img.shields.io/github/actions/workflow/status/pietrozullo/mcp-use/testprimitives.yml?job=sampling&label=Sampling&style=flat)](https://github.com/pietrozullo/mcp-use/actions/workflows/testprimitives.yml) |
50-
| **Transports** | [![Stdio](https://img.shields.io/github/actions/workflow/status/pietrozullo/mcp-use/transportstests.yml?job=stdio&label=Stdio&style=flat)](https://github.com/pietrozullo/mcp-use/actions/workflows/transportstests.yml) [![SSE](https://img.shields.io/github/actions/workflow/status/pietrozullo/mcp-use/transportstests.yml?job=sse&label=SSE&style=flat)](https://github.com/pietrozullo/mcp-use/actions/workflows/transportstests.yml) [![Streamable HTTP](https://img.shields.io/github/actions/workflow/status/pietrozullo/mcp-use/transportstests.yml?job=streamableHttp&label=Streamable%20HTTP&style=flat)](https://github.com/pietrozullo/mcp-use/actions/workflows/transportstests.yml) |
51-
52-
## Features
42+
# Features
5343

44+
## ✨ Key Features
5445
<table>
5546
<tr>
5647
<th width="400">Feature</th>
@@ -121,7 +112,6 @@ pip install langchain-openai
121112
# For Anthropic
122113
pip install langchain-anthropic
123114
```
124-
125115
For other providers, check the [LangChain chat models documentation](https://python.langchain.com/docs/integrations/chat/) and add your API keys for the provider you want to use to your `.env` file.
126116

127117
```bash
@@ -677,7 +667,7 @@ async def main():
677667

678668
# Create a custom LangChain agent
679669
llm_with_tools = llm.bind_tools(tools)
680-
result = await llm_with_tools.ainvoke("What tools do you have available ? ")
670+
result = await llm_with_tools.ainvoke("What tools do you have avilable ? ")
681671
print(result)
682672

683673

@@ -758,6 +748,7 @@ Thanks to all our amazing contributors!
758748
<img src="https://contrib.rocks/image?repo=mcp-use/mcp-use" />
759749
</a>
760750

751+
761752
## Top Starred Dependents
762753

763754
<!-- gh-dependents-info-used-by-start -->
@@ -820,7 +811,6 @@ Thanks to all our amazing contributors!
820811
# License
821812

822813
MIT
823-
824814
# Citation
825815

826816
If you use MCP-Use in your research or project, please cite:
@@ -834,5 +824,3 @@ If you use MCP-Use in your research or project, please cite:
834824
url = {https://github.com/pietrozullo/mcp-use}
835825
}
836826
```
837-
838-
<img referrerpolicy="no-referrer-when-downgrade" src="https://static.scarf.sh/a.png?x-pxid=732589b6-6850-4b8c-aa25-906c0979e426&page=README.md" />

client.py

Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
from __future__ import annotations
2+
3+
import asyncio
4+
import os
5+
import traceback
6+
from typing import Union, Optional
7+
from dotenv import load_dotenv
8+
from langchain_openai import ChatOpenAI
9+
from mcp_use import MCPAgent, MCPClient
10+
11+
# Načítanie environment variables
12+
load_dotenv()
13+
14+
15+
async def main():
16+
config = {
17+
"mcpServers": {
18+
"wordpress_server": {
19+
"url": os.getenv("MCP_BASE_URL"),
20+
"headers": {
21+
"Authorization": f"Bearer {os.getenv('JWT_TOKEN')}",
22+
"Content-Type": "application/json"
23+
}
24+
}
25+
}
26+
}
27+
28+
# Vytvorenie MCP klienta
29+
client = MCPClient.from_dict(config)
30+
31+
# Explicitné vytvorenie sessions s error handlingom
32+
print("🔍 Vytváram MCP sessions...")
33+
try:
34+
sessions = await client.create_all_sessions()
35+
print(f"✅ Vytvorené sessions: {list(sessions.keys())}")
36+
37+
# Overenie dostupných nástrojov
38+
for name, session in sessions.items():
39+
tools = session.connector.tools
40+
print(f"🔧 Server '{name}' má {len(tools)} nástrojov")
41+
42+
except Exception as e:
43+
print(f"❌ Chyba pri vytváraní sessions: {e}")
44+
traceback.print_exc()
45+
return
46+
47+
# Vytvorenie OpenAI LLM
48+
llm = ChatOpenAI(
49+
model="gpt-4.1",
50+
api_key=os.getenv("OPENAI_API_KEY")
51+
)
52+
53+
# Vytvorenie MCP agenta s explicitným error handlingom
54+
print("🔍 Vytváram MCPAgent...")
55+
try:
56+
agent = MCPAgent(
57+
llm=llm,
58+
client=client,
59+
max_steps=15,
60+
memory_enabled=True,
61+
auto_initialize=False # Nepovoliť auto-init kvôli chybe
62+
)
63+
print("✅ MCPAgent vytvorený")
64+
65+
# Manuálna inicializácia s detailným logovaním
66+
print("🔍 Inicializujem agent...")
67+
await agent.initialize()
68+
print("✅ Agent inicializovaný")
69+
70+
# Overenie či má agent _tools atribút
71+
if hasattr(agent, '_tools'):
72+
print(f"✅ Agent má _tools: {len(agent._tools) if agent._tools else 0}")
73+
else:
74+
print("❌ Agent nemá _tools atribút!")
75+
return
76+
77+
except Exception as e:
78+
print(f"❌ Chyba pri vytváraní/inicializácii agenta: {e}")
79+
traceback.print_exc()
80+
return
81+
82+
print("\n🚀 WordPress MCP Chat Bot spustený!")
83+
print("💬 Napíšte 'exit' pre ukončenie chatu")
84+
print("🔧 Môžete sa pýtať na WordPress funkcie, nástroje, príspevky, atď.")
85+
print("-" * 60)
86+
87+
try:
88+
# Hlavný chat loop s detailným error handlingom
89+
while True:
90+
user_input = input("\n👤 Vy: ").strip()
91+
92+
# Rozšírená validácia vstupu
93+
if not user_input or user_input.isspace():
94+
print("⚠️ Zadajte prosím platnú otázku alebo 'exit' pre ukončenie.")
95+
continue
96+
97+
if user_input.lower() in ['exit', 'quit', 'bye', 'koniec']:
98+
print("\n👋 Ďakujem za rozhovor! Chat ukončený.")
99+
break
100+
101+
if user_input.lower() in ['clear', 'reset', 'vymazat']:
102+
if hasattr(agent, 'clear_conversation_history'):
103+
agent.clear_conversation_history()
104+
print("🧹 História konverzácie vymazaná.")
105+
else:
106+
print("⚠️ Clear history nie je dostupné")
107+
continue
108+
109+
# Debug info pred spustením
110+
if user_input.lower() == 'debug':
111+
print(f"🔍 Debug info:")
112+
print(f" - Agent má _tools: {hasattr(agent, '_tools')}")
113+
print(f" - Agent._tools je: {type(getattr(agent, '_tools', None))}")
114+
print(f" - Počet nástrojov: {len(getattr(agent, '_tools', []))}")
115+
print(f" - Client sessions: {len(client.sessions)}")
116+
continue
117+
118+
print("\n🤖 Bot: ", end="", flush=True)
119+
120+
try:
121+
# Detailné logovanie pred agent.run
122+
print(f"[DEBUG] Spúšťam agent.run s inputom: '{user_input[:50]}...'")
123+
124+
# Overenie pred spustením
125+
if not hasattr(agent, '_tools') or agent._tools is None:
126+
print("\n❌ Agent nemá inicializované nástroje!")
127+
continue
128+
129+
result = await agent.run(
130+
user_input,
131+
manage_connector=False # Connector už je vytvorený
132+
)
133+
print(result)
134+
135+
except Exception as e:
136+
print(f"\n❌ Chyba pri spracovaní otázky: {e}")
137+
print(f"📝 Typ chyby: {type(e).__name__}")
138+
print("\n🔍 Úplný traceback:")
139+
traceback.print_exc()
140+
print("\n🔄 Skúste to znovu alebo zadajte inú otázku.")
141+
142+
except KeyboardInterrupt:
143+
print("\n\n⚠️ Chat prerušený používateľom (Ctrl+C)")
144+
145+
except Exception as e:
146+
print(f"\n❌ Neočakávaná chyba: {e}")
147+
traceback.print_exc()
148+
149+
finally:
150+
print("\n🧹 Zatváram spojenia...")
151+
try:
152+
if client.sessions:
153+
await client.close_all_sessions()
154+
print("✅ Spojenia zatvorené.")
155+
except Exception as e:
156+
print(f"⚠️ Chyba pri zatváraní: {e}")
157+
158+
159+
if __name__ == "__main__":
160+
asyncio.run(main())

0 commit comments

Comments
 (0)