Skip to content

Commit 3dfd636

Browse files
committed
ran black on python files
1 parent 60bf0c9 commit 3dfd636

File tree

12 files changed

+940
-584
lines changed

12 files changed

+940
-584
lines changed

services/agent-environment/dev_scripts/debug_and_concurrency_tests/get_running_servers.py

Lines changed: 39 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
Useful as a quick check to see if some mcp servers errored during startup.
44
Does not check that they work tho (e.g. api key could be invalid and /call_tool will fail, but mcp server is running).
55
6-
Usage (requires server to be running on port 1984, you can do "make run" or "make run-docker"):
6+
Usage (requires server to be running on port 1984, you can do "make run" or "make run-docker"):
77
uv run python get_running_servers.py
88
"""
99

@@ -12,92 +12,100 @@
1212
import os
1313
import sys
1414

15+
1516
def load_configured_servers():
1617
"""Load the configured servers from mcp_client.py"""
1718
try:
1819
# Add the src directory to Python path so we can import the module
19-
src_path = os.path.join(os.path.dirname(__file__), '../../src')
20+
src_path = os.path.join(os.path.dirname(__file__), "../../src")
2021
if src_path not in sys.path:
2122
sys.path.insert(0, src_path)
22-
23+
2324
# Import the mcp_client module directly
2425
from agent_environment.mcp_client import config
25-
26+
2627
# Extract server names from the config
2728
configured_servers = set(config["mcpServers"].keys())
2829
return configured_servers
29-
30+
3031
except ImportError as e:
31-
raise Exception(f"Could not import mcp_client module: {e}. Are you using \"uv run ...\"?")
32+
raise Exception(
33+
f'Could not import mcp_client module: {e}. Are you using "uv run ..."?'
34+
)
3235
except KeyError as e:
3336
raise Exception(f"Config structure error: {e}")
3437
except Exception as e:
3538
raise Exception(f"Error loading configured servers: {e}")
3639

40+
3741
def main():
38-
load_configured_servers() # to trigger the import warning at the top of this script
42+
load_configured_servers() # to trigger the import warning at the top of this script
3943

4044
try:
4145
# Step 1: Run the curl script and extract tool names
4246
print("Calling ./curl_scripts/mcp__list_tools.sh to get running mcp servers...")
43-
47+
4448
# Run the command: ./curl_scripts/mcp__list_tools.sh | jq | grep "^ \"name"
4549
curl_script_path = "./curl_scripts/mcp__list_tools.sh"
46-
50+
4751
if not os.path.exists(curl_script_path):
4852
print(f"Error: {curl_script_path} not found")
4953
sys.exit(1)
50-
54+
5155
# Run the command pipeline
52-
result = subprocess.run([
53-
"bash", "-c",
54-
f"{curl_script_path} | jq | grep '^ \"name'"
55-
], capture_output=True, text=True, check=True)
56-
56+
result = subprocess.run(
57+
["bash", "-c", f"{curl_script_path} | jq | grep '^ \"name'"],
58+
capture_output=True,
59+
text=True,
60+
check=True,
61+
)
62+
5763
tool_names_content = result.stdout
58-
64+
5965
# Write to temporary file
6066
with open("tool-names.txt", "w") as f:
6167
f.write(tool_names_content)
62-
68+
6369
# Step 2: Process with regex to extract server names
64-
pattern = r'.*\"([a-zA-Z0-9\-]+)_.*'
70+
pattern = r".*\"([a-zA-Z0-9\-]+)_.*"
6571
server_names = set()
66-
72+
6773
for line in tool_names_content.splitlines():
6874
line = line.strip()
6975
if line:
7076
match = re.search(pattern, line)
7177
if match:
7278
server_name = match.group(1)
7379
server_names.add(server_name)
74-
80+
7581
# Step 3: Remove duplicates (already done with set) and save
7682
print(f"\nFound {len(server_names)} unique running servers\n")
77-
83+
7884
# Sort for consistent output
7985
sorted_servers = sorted(server_names)
80-
86+
8187
print(f"Running servers: {sorted_servers}\n")
82-
88+
8389
# Step 3.5: Compare with configured servers
84-
90+
8591
configured_servers = load_configured_servers()
8692
not_running = configured_servers - server_names
87-
93+
8894
if not_running:
8995
print(f"⚠️ CONFIGURED BUT NOT RUNNING ({len(not_running)} servers):")
9096
for server in sorted(not_running):
9197
print(f" ❌ {server}")
9298
else:
93-
print(f"✅ All {len(configured_servers)} mcp servers in mcp_client.py are running!")
94-
99+
print(
100+
f"✅ All {len(configured_servers)} mcp servers in mcp_client.py are running!"
101+
)
102+
95103
# Step 4: Clean up temporary file
96104
if os.path.exists("tool-names.txt"):
97105
os.remove("tool-names.txt")
98-
106+
99107
print("\nDone!")
100-
108+
101109
except subprocess.CalledProcessError as e:
102110
print(f"Error running command: {e}")
103111
print(f"stdout: {e.stdout}")
@@ -107,5 +115,6 @@ def main():
107115
print(f"Error: {e}")
108116
sys.exit(1)
109117

118+
110119
if __name__ == "__main__":
111-
main()
120+
main()

services/agent-environment/src/agent_environment/main.py

Lines changed: 30 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,11 @@
1919

2020
# Create cache with appropriate settings for the use case
2121
tool_cache = Cache(
22-
maxsize=10000, # Max 10000 unique requests (fits about 2000 tasks)
23-
ttl=CACHE_TTL_HOURS * 60 * 60, # 48 hours TTL by default (but each item will have some slight variation)
24-
enable_stats=True # Track cache performance
22+
maxsize=10000, # Max 10000 unique requests (fits about 2000 tasks)
23+
ttl=CACHE_TTL_HOURS
24+
* 60
25+
* 60, # 48 hours TTL by default (but each item will have some slight variation)
26+
enable_stats=True, # Track cache performance
2527
)
2628

2729
# Tool name mappings - maps old invalid names to correct names
@@ -126,40 +128,45 @@ def should_cache_tool(tool_name: str) -> bool:
126128
server_name = tool_name.split("_", 1)[0]
127129
return server_name in CACHEABLE_SERVERS
128130

131+
129132
def generate_cache_key(tool_name: str, tool_args: dict) -> str:
130133
"""Generate consistent cache key from tool call parameters."""
131-
cache_data = {
132-
"tool_name": tool_name,
133-
"tool_args": tool_args
134-
}
134+
cache_data = {"tool_name": tool_name, "tool_args": tool_args}
135135
cache_str = json.dumps(cache_data, sort_keys=True)
136136
return hashlib.md5(cache_str.encode()).hexdigest()
137137

138+
138139
@app.post("/call-tool")
139140
async def call_tool(
140141
request: CallToolRequest,
141142
) -> list[mcp.types.ContentBlock]:
142143
"""Call a specific tool with the provided arguments."""
143-
144+
144145
mapped_tool_name = TOOL_NAME_MAPPINGS.get(request.tool_name, request.tool_name)
145-
146+
146147
# Generate cache key
147148
cache_key = generate_cache_key(mapped_tool_name, request.tool_args)
148-
149+
149150
# Check cache first
150151
cached_result = tool_cache.get(cache_key)
151-
if cached_result is not None and request.use_cache and should_cache_tool(mapped_tool_name):
152+
if (
153+
cached_result is not None
154+
and request.use_cache
155+
and should_cache_tool(mapped_tool_name)
156+
):
152157
logger.info(f"Returning cached result for tool '{request.tool_name}'")
153158
return cached_result
154-
159+
155160
async with client:
156161
try:
157162
result = await client.call_tool(mapped_tool_name, request.tool_args)
158163

159164
# Check for errors first (FastMCP best practice)
160165
if result.is_error:
161166
error_msg = "Unknown error"
162-
if result.content and isinstance(result.content[0], mcp.types.TextContent):
167+
if result.content and isinstance(
168+
result.content[0], mcp.types.TextContent
169+
):
163170
error_msg = result.content[0].text
164171
raise HTTPException(
165172
status_code=500,
@@ -172,24 +179,26 @@ async def call_tool(
172179
# TTL is 70-100% of default TTL, to avoid all items expiring at the same time
173180
random_ttl = int(CACHE_TTL_HOURS * 60 * 60 * random.uniform(0.7, 1.0))
174181
tool_cache.set(cache_key, content_blocks, ttl=random_ttl)
175-
182+
176183
return content_blocks
177-
184+
178185
except Exception as e:
179186
raise HTTPException(
180187
status_code=500,
181188
detail=f"Failed to call tool '{request.tool_name}': {str(e)}",
182189
)
183190

191+
184192
@app.get("/cache-stats")
185193
async def get_cache_stats():
186194
"""Get cache statistics for monitoring."""
187195
return {
188196
"cache_size": len(tool_cache),
189197
"max_size": tool_cache.maxsize,
190-
"ttl_seconds": tool_cache.ttl
198+
"ttl_seconds": tool_cache.ttl,
191199
}
192200

201+
193202
@app.post("/cache-clear")
194203
async def clear_cache():
195204
"""Clear the entire cache."""
@@ -201,7 +210,7 @@ async def clear_cache():
201210
async def get_enabled_servers() -> dict[str, Any]:
202211
"""Get list of configured MCP servers with their status (OK or ERROR_NOT_ONLINE)."""
203212
configured = set(config.get("mcpServers", {}).keys())
204-
213+
205214
async with client:
206215
try:
207216
tools = await client.list_tools()
@@ -211,18 +220,18 @@ async def get_enabled_servers() -> dict[str, Any]:
211220
if "_" in tool.name:
212221
server_name = tool.name.split("_", 1)[0]
213222
live_servers.add(server_name)
214-
223+
215224
# Build status list for each configured server
216225
servers = [
217226
(name, "OK" if name in live_servers else "ERROR_NOT_ONLINE")
218227
for name in sorted(configured)
219228
]
220-
229+
221230
return {
222231
"servers": servers,
223232
"total": len(configured),
224233
"online": len(live_servers),
225-
"offline": len(configured - live_servers)
234+
"offline": len(configured - live_servers),
226235
}
227236
except Exception as e:
228237
raise HTTPException(
@@ -234,6 +243,7 @@ async def get_enabled_servers() -> dict[str, Any]:
234243
async def health() -> dict[str, Any]:
235244
"""Simple health check that verifies client is also ok. Timeout is 5 seconds."""
236245
try:
246+
237247
async def _health_check_with_client():
238248
async with client:
239249
return {

0 commit comments

Comments
 (0)