Skip to content

Commit 9375927

Browse files
committed
Remove usages of asyncio in tests
1 parent 4a6c5a5 commit 9375927

File tree

15 files changed

+135
-152
lines changed

15 files changed

+135
-152
lines changed

examples/clients/async-reconnect-client/mcp_async_reconnect_client/client.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
import asyncio
2-
1+
import anyio
32
import click
43
from mcp import ClientSession, types
54
from mcp.client.streamable_http import streamablehttp_client
@@ -30,7 +29,7 @@ async def call_async_tool(session: ClientSession, token: str | None):
3029
print(f"Operation failed: {status.error}")
3130
break
3231

33-
await asyncio.sleep(0.5)
32+
await anyio.sleep(0.5)
3433

3534

3635
async def run_session(endpoint: str, token: str | None):
@@ -44,4 +43,4 @@ async def run_session(endpoint: str, token: str | None):
4443
@click.option("--endpoint", default="http://127.0.0.1:8000/mcp", help="Endpoint to connect to")
4544
@click.option("--token", default=None, help="Operation token to resume with")
4645
def main(endpoint: str, token: str | None):
47-
asyncio.run(run_session(endpoint, token))
46+
anyio.run(run_session, endpoint, token)

examples/servers/simple-tool-async/mcp_simple_tool_async/server.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
import asyncio
2-
1+
import anyio
32
import click
43
import mcp.types as types
54
import uvicorn
@@ -15,7 +14,7 @@ async def fetch_website(
1514
) -> list[types.ContentBlock]:
1615
headers = {"User-Agent": "MCP Test Server (github.com/modelcontextprotocol/python-sdk)"}
1716
async with create_mcp_http_client(headers=headers) as client:
18-
await asyncio.sleep(5)
17+
await anyio.sleep(5)
1918
response = await client.get(url)
2019
response.raise_for_status()
2120
return [types.TextContent(type="text", text=response.text)]

examples/snippets/clients/async_elicitation_client.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@
55
uv run async-elicitation-client
66
"""
77

8-
import asyncio
98
import os
109

10+
import anyio
11+
1112
from mcp import ClientSession, StdioServerParameters, types
1213
from mcp.client.stdio import stdio_client
1314
from mcp.shared.context import RequestContext
@@ -70,7 +71,7 @@ async def test_process_with_confirmation(session: ClientSession):
7071
print(f"Operation failed: {status.error}")
7172
break
7273

73-
await asyncio.sleep(0.3)
74+
await anyio.sleep(0.3)
7475

7576

7677
async def test_file_operation(session: ClientSession):
@@ -97,7 +98,7 @@ async def test_file_operation(session: ClientSession):
9798
print(f"File operation failed: {status.error}")
9899
break
99100

100-
await asyncio.sleep(0.3)
101+
await anyio.sleep(0.3)
101102

102103

103104
async def run():
@@ -115,4 +116,4 @@ async def run():
115116

116117

117118
if __name__ == "__main__":
118-
asyncio.run(run())
119+
anyio.run(run)

examples/snippets/clients/async_progress_client.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@
55
uv run async-progress-client
66
"""
77

8-
import asyncio
98
import os
109

10+
import anyio
11+
1112
from mcp import ClientSession, StdioServerParameters, types
1213
from mcp.client.stdio import stdio_client
1314

@@ -58,7 +59,7 @@ async def progress_callback(progress: float, total: float | None, message: str |
5859
print(f"Operation failed: {status.error}")
5960
break
6061

61-
await asyncio.sleep(0.3)
62+
await anyio.sleep(0.3)
6263

6364
print(f"Received {len(progress_updates)} progress updates")
6465

@@ -91,7 +92,7 @@ async def test_data_pipeline(session: ClientSession):
9192
print(f"Pipeline failed: {status.error}")
9293
break
9394

94-
await asyncio.sleep(0.3)
95+
await anyio.sleep(0.3)
9596

9697

9798
async def run():
@@ -107,4 +108,4 @@ async def run():
107108

108109

109110
if __name__ == "__main__":
110-
asyncio.run(run())
111+
anyio.run(run)

examples/snippets/clients/async_sampling_client.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@
55
uv run async-sampling-client
66
"""
77

8-
import asyncio
98
import os
109

10+
import anyio
11+
1112
from mcp import ClientSession, StdioServerParameters, types
1213
from mcp.client.stdio import stdio_client
1314
from mcp.shared.context import RequestContext
@@ -77,7 +78,7 @@ async def test_content_generation(session: ClientSession):
7778
print(f"Generation failed: {status.error}")
7879
break
7980

80-
await asyncio.sleep(0.3)
81+
await anyio.sleep(0.3)
8182

8283

8384
async def test_multi_step_generation(session: ClientSession):
@@ -107,7 +108,7 @@ async def test_multi_step_generation(session: ClientSession):
107108
print(f"Multi-step generation failed: {status.error}")
108109
break
109110

110-
await asyncio.sleep(0.3)
111+
await anyio.sleep(0.3)
111112

112113

113114
async def run():
@@ -123,4 +124,4 @@ async def run():
123124

124125

125126
if __name__ == "__main__":
126-
asyncio.run(run())
127+
anyio.run(run)

examples/snippets/clients/async_tool_client.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@
55
uv run async-tool-client
66
"""
77

8-
import asyncio
98
import os
109

10+
import anyio
11+
1112
from mcp import ClientSession, StdioServerParameters, types
1213
from mcp.client.stdio import stdio_client
1314

@@ -44,7 +45,7 @@ async def call_async_tool(session: ClientSession):
4445
print(f"Operation failed: {status.error}")
4546
break
4647

47-
await asyncio.sleep(0.5)
48+
await anyio.sleep(0.5)
4849

4950

5051
async def run():
@@ -56,4 +57,4 @@ async def run():
5657

5758

5859
if __name__ == "__main__":
59-
asyncio.run(run())
60+
anyio.run(run)

examples/snippets/servers/async_tool_basic.py

Lines changed: 8 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -5,21 +5,22 @@
55
uv run server async_tool_basic stdio
66
"""
77

8-
import asyncio
8+
import anyio
99

1010
from mcp.server.fastmcp import Context, FastMCP
11+
from mcp.server.session import ServerSession
1112

1213
mcp = FastMCP("Async Tool Basic")
1314

1415

1516
@mcp.tool(invocation_modes=["async"])
16-
async def analyze_data(dataset: str, ctx: Context) -> str: # type: ignore[type-arg]
17+
async def analyze_data(dataset: str, ctx: Context[ServerSession, None]) -> str:
1718
"""Analyze a dataset asynchronously with progress updates."""
1819
await ctx.info(f"Starting analysis of {dataset}")
1920

2021
# Simulate analysis with progress updates
2122
for i in range(5):
22-
await asyncio.sleep(0.5)
23+
await anyio.sleep(0.5)
2324
progress = (i + 1) / 5
2425
await ctx.report_progress(progress, 1.0, f"Processing step {i + 1}/5")
2526

@@ -28,21 +29,11 @@ async def analyze_data(dataset: str, ctx: Context) -> str: # type: ignore[type-
2829

2930

3031
@mcp.tool(invocation_modes=["sync", "async"])
31-
def process_text(text: str, ctx: Context | None = None) -> str: # type: ignore[type-arg]
32+
async def process_text(text: str, ctx: Context[ServerSession, None]) -> str:
3233
"""Process text in sync or async mode."""
33-
if ctx:
34-
# Async mode with context
35-
import asyncio
36-
37-
async def async_processing():
38-
await ctx.info(f"Processing text asynchronously: {text[:20]}...")
39-
await asyncio.sleep(0.3)
40-
41-
try:
42-
loop = asyncio.get_event_loop()
43-
loop.create_task(async_processing())
44-
except RuntimeError:
45-
pass
34+
35+
await ctx.info(f"Processing text asynchronously: {text[:20]}...")
36+
await anyio.sleep(0.3)
4637

4738
return f"Processed: {text.upper()}"
4839

examples/snippets/servers/async_tool_elicitation.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,11 @@
55
uv run server async_tool_elicitation stdio
66
"""
77

8-
import asyncio
9-
8+
import anyio
109
from pydantic import BaseModel, Field
1110

1211
from mcp.server.fastmcp import Context, FastMCP
12+
from mcp.server.session import ServerSession
1313

1414
mcp = FastMCP("Async Tool Elicitation")
1515

@@ -32,12 +32,12 @@ class FileOperationChoice(BaseModel):
3232

3333

3434
@mcp.tool(invocation_modes=["async"])
35-
async def process_with_confirmation(operation: str, ctx: Context) -> str: # type: ignore[type-arg]
35+
async def process_with_confirmation(operation: str, ctx: Context[ServerSession, None]) -> str:
3636
"""Process an operation that requires user confirmation."""
3737
await ctx.info(f"Starting operation: {operation}")
3838

3939
# Simulate some initial processing
40-
await asyncio.sleep(0.5)
40+
await anyio.sleep(0.5)
4141
await ctx.report_progress(0.3, 1.0, "Initial processing complete")
4242

4343
# Ask user for preferences
@@ -51,7 +51,7 @@ async def process_with_confirmation(operation: str, ctx: Context) -> str: # typ
5151
await ctx.info(f"Continuing with {result.data.priority_level} priority")
5252
# Simulate processing based on user choice
5353
processing_time = {"low": 0.5, "normal": 1.0, "high": 1.5}.get(result.data.priority_level, 1.0)
54-
await asyncio.sleep(processing_time)
54+
await anyio.sleep(processing_time)
5555
await ctx.report_progress(1.0, 1.0, "Operation complete")
5656
return f"Operation '{operation}' completed successfully with {result.data.priority_level} priority"
5757
else:
@@ -63,12 +63,12 @@ async def process_with_confirmation(operation: str, ctx: Context) -> str: # typ
6363

6464

6565
@mcp.tool(invocation_modes=["async"])
66-
async def file_operation(file_path: str, operation_type: str, ctx: Context) -> str: # type: ignore[type-arg]
66+
async def file_operation(file_path: str, operation_type: str, ctx: Context[ServerSession, None]) -> str:
6767
"""Perform file operation with user confirmation."""
6868
await ctx.info(f"Analyzing file: {file_path}")
6969

7070
# Simulate initial analysis
71-
await asyncio.sleep(1)
71+
await anyio.sleep(1)
7272
await ctx.report_progress(0.3, 1.0, "File analysis complete")
7373

7474
# Simulate finding something that requires user confirmation
@@ -84,11 +84,11 @@ async def file_operation(file_path: str, operation_type: str, ctx: Context) -> s
8484
if result.data.confirm_operation:
8585
if result.data.backup_first:
8686
await ctx.info("Creating backup first...")
87-
await asyncio.sleep(0.5)
87+
await anyio.sleep(0.5)
8888
await ctx.report_progress(0.7, 1.0, "Backup created")
8989

9090
await ctx.info(f"Performing {operation_type} operation...")
91-
await asyncio.sleep(1)
91+
await anyio.sleep(1)
9292
await ctx.report_progress(1.0, 1.0, "Operation complete")
9393

9494
backup_msg = " (with backup)" if result.data.backup_first else " (no backup)"

examples/snippets/servers/async_tool_immediate.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,11 @@
55
uv run server async_tool_immediate stdio
66
"""
77

8-
import asyncio
8+
import anyio
99

1010
from mcp import types
1111
from mcp.server.fastmcp import Context, FastMCP
12+
from mcp.server.session import ServerSession
1213

1314
mcp = FastMCP("Async Tool Immediate")
1415

@@ -19,13 +20,13 @@ async def provide_immediate_feedback(operation: str) -> list[types.ContentBlock]
1920

2021

2122
@mcp.tool(invocation_modes=["async"], immediate_result=provide_immediate_feedback)
22-
async def long_analysis(operation: str, ctx: Context) -> str: # type: ignore[type-arg]
23+
async def long_analysis(operation: str, ctx: Context[ServerSession, None]) -> str:
2324
"""Perform long-running analysis with immediate user feedback."""
2425
await ctx.info(f"Beginning {operation} analysis")
2526

2627
# Simulate long-running work
2728
for i in range(4):
28-
await asyncio.sleep(1)
29+
await anyio.sleep(1)
2930
progress = (i + 1) / 4
3031
await ctx.report_progress(progress, 1.0, f"Analysis step {i + 1}/4")
3132

examples/snippets/servers/async_tool_progress.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,16 @@
55
uv run server async_tool_progress stdio
66
"""
77

8-
import asyncio
8+
import anyio
99

1010
from mcp.server.fastmcp import Context, FastMCP
11+
from mcp.server.session import ServerSession
1112

1213
mcp = FastMCP("Async Tool Progress")
1314

1415

1516
@mcp.tool(invocation_modes=["async"])
16-
async def batch_process(items: list[str], ctx: Context) -> list[str]: # type: ignore[type-arg]
17+
async def batch_process(items: list[str], ctx: Context[ServerSession, None]) -> list[str]:
1718
"""Process a batch of items with detailed progress reporting."""
1819
await ctx.info(f"Starting batch processing of {len(items)} items")
1920

@@ -24,7 +25,7 @@ async def batch_process(items: list[str], ctx: Context) -> list[str]: # type: i
2425

2526
# Simulate variable processing time
2627
processing_time = 0.3 + (len(item) * 0.1)
27-
await asyncio.sleep(processing_time)
28+
await anyio.sleep(processing_time)
2829

2930
# Report progress for this item
3031
progress = (i + 1) / len(items)
@@ -41,7 +42,7 @@ async def batch_process(items: list[str], ctx: Context) -> list[str]: # type: i
4142

4243

4344
@mcp.tool(invocation_modes=["async"])
44-
async def data_pipeline(dataset: str, operations: list[str], ctx: Context) -> dict[str, str]: # type: ignore[type-arg]
45+
async def data_pipeline(dataset: str, operations: list[str], ctx: Context[ServerSession, None]) -> dict[str, str]:
4546
"""Execute a data processing pipeline with progress updates."""
4647
await ctx.info(f"Starting data pipeline for {dataset}")
4748

@@ -53,7 +54,7 @@ async def data_pipeline(dataset: str, operations: list[str], ctx: Context) -> di
5354

5455
# Simulate processing time that increases with complexity
5556
processing_time = 0.5 + (i * 0.2)
56-
await asyncio.sleep(processing_time)
57+
await anyio.sleep(processing_time)
5758

5859
# Report progress
5960
progress = (i + 1) / total_ops

0 commit comments

Comments
 (0)