Skip to content

Commit f3fa6b5

Browse files
author
BrokenDuck
committed
Add code tests with file
1 parent 792d080 commit f3fa6b5

File tree

2 files changed

+116
-16
lines changed

2 files changed

+116
-16
lines changed

mcp-run-python/src/runCode.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,7 @@ const LogLevels: LoggingLevel[] = [
206206
export function resolveMountDir(mountDir: string): string {
207207
// Base dir created by emscriptem
208208
// See https://emscripten.org/docs/api_reference/Filesystem-API.html#file-system-api
209-
const baseDir = '/home/web_user'
209+
const baseDir = '/home/pyodide'
210210

211211
if (mountDir.trim() === '') {
212212
return path.join(baseDir, 'persistent')

mcp-run-python/test_mcp_servers.py

Lines changed: 115 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,17 @@ class McpTools(StrEnum):
4343
RETRIEVE_FILE = 'retrieve_file'
4444

4545

46-
LOREM_IPSUM = """But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?
47-
48-
On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains.
46+
CSV_DATA = """Name,Age,Department,Salary
47+
Alice,25,Engineering,60000
48+
Bob,32,Marketing,52000
49+
Charlie,29,Engineering,70000
50+
Diana,45,HR,65000
51+
Ethan,35,Marketing,58000
52+
Fiona,28,Engineering,72000
53+
George,40,HR,64000
54+
Hannah,31,Engineering,68000
55+
Ian,38,Marketing,61000
56+
Julia,27,HR,59000
4957
"""
5058

5159
BASE_64_IMAGE = 'iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAIAAADTED8xAAAEX0lEQVR4nOzdO8vX9R/HcS/56f8PWotGQkPBBUWESCQYNJR0GjIn6UBTgUMZTiGE4ZgRVKNkuDSEFtgBQqIiKunkEFdkWLmEBQUWiNUQYd2KNwTPx+MGvD7Tk/f2/S7O7tmyatKnJx8b3f/p6EOj+5euu2Z0/+Sxt0f3N++9fHR/+57/j+7vuPuT0f3Vo+vwHycA0gRAmgBIEwBpAiBNAKQJgDQBkCYA0gRAmgBIEwBpAiBNAKQJgDQBkCYA0gRAmgBIEwBpAiBNAKQJgDQBkCYA0gRAmgBIEwBpAiBNAKQtDr561+gDpzf9PLp/4eNzo/uXzv41uv/BM0+O7h9/bsPo/vqPdo3u7965GN13AUgTAGkCIE0ApAmANAGQJgDSBECaAEgTAGkCIE0ApAmANAGQJgDSBECaAEgTAGkCIE0ApAmANAGQJgDSBECaAEgTAGkCIE0ApAmANAGQJgDSlh5ce+XoA9+eODK6v3r7naP7b31zaHT/4p+3jO4f2/Tb6P7K41tH9zff+8LovgtAmgBIEwBpAiBNAKQJgDQBkCYA0gRAmgBIEwBpAiBNAKQJgDQBkCYA0gRAmgBIEwBpAiBNAKQJgDQBkCYA0gRAmgBIEwBpAiBNAKQJgDQBkLb09ZmLow8sb1ke3d92YXR+1dO7PhzdX7f2xtH9Q5fN/t/g2j9eHt3/cc350X0XgDQBkCYA0gRAmgBIEwBpAiBNAKQJgDQBkCYA0gRAmgBIEwBpAiBNAKQJgDQBkCYA0gRAmgBIEwBpAiBNAKQJgDQBkCYA0gRAmgBIEwBpAiBtcf3eW0cfePTE7Pf1D9yxMrq/4YrR+VWvnN84uv/lvs2j+2v3nx3dv3rT/0b3XQDSBECaAEgTAGkCIE0ApAmANAGQJgDSBECaAEgTAGkCIE0ApAmANAGQJgDSBECaAEgTAGkCIE0ApAmANAGQJgDSBECaAEgTAGkCIE0ApAmAtKWrzq0ffeD312f339h5ZnT/npsPj+7//cPDo/un739idP/Xg5+P7j/y/G2j+y4AaQIgTQCkCYA0AZAmANIEQJoASBMAaQIgTQCkCYA0AZAmANIEQJoASBMAaQIgTQCkCYA0AZAmANIEQJoASBMAaQIgTQCkCYA0AZAmANIEQNpi/5FfRh94753XRvcP7F0zuv/V7e+O7t906v3R/WdP/zO6f9/ixdH9G3Z/NrrvApAmANIEQJoASBMAaQIgTQCkCYA0AZAmANIEQJoASBMAaQIgTQCkCYA0AZAmANIEQJoASBMAaQIgTQCkCYA0AZAmANIEQJoASBMAaQIgTQCkLb25vDL6wLoHjo7ur7z03ej++u+fGt0/vm/2+/dfHF4e3d9xauPo/taN20b3XQDSBECaAEgTAGkCIE0ApAmANAGQJgDSBECaAEgTAGkCIE0ApAmANAGQJgDSBECaAEgTAGkCIE0ApAmANAGQJgDSBECaAEgTAGkCIE0ApAmAtH8DAAD//9drYGg9ROu9AAAAAElFTkSuQmCC'
@@ -347,17 +355,17 @@ async def test_upload_files(
347355

348356
match uri_type:
349357
case 'file':
350-
filename = 'lorem.txt'
351-
lorem_file = tmp_path / filename
352-
lorem_file.write_text(LOREM_IPSUM)
358+
filename = 'data.csv'
359+
data_file = tmp_path / filename
360+
data_file.write_text(CSV_DATA)
353361

354362
result = await mcp_session.call_tool(
355-
McpTools.UPLOAD_FILE_FROM_URI, {'uri': f'file://{str(lorem_file)}', 'filename': filename}
363+
McpTools.UPLOAD_FILE_FROM_URI, {'uri': f'file://{str(data_file)}', 'filename': filename}
356364
)
357365

358366
case 'http':
359-
filename = 'lorem.txt'
360-
with self.serve_file_once(LOREM_IPSUM.encode()) as url:
367+
filename = 'data.csv'
368+
with self.serve_file_once(CSV_DATA.encode()) as url:
361369
result = await mcp_session.call_tool(
362370
McpTools.UPLOAD_FILE_FROM_URI, {'uri': url, 'filename': filename}
363371
)
@@ -369,12 +377,12 @@ async def test_upload_files(
369377
assert str(content.uri) == f'file:///{filename}'
370378
assert content.name == filename
371379
assert content.mimeType is not None
372-
assert content.mimeType.startswith('text/plain')
380+
assert content.mimeType.startswith('text/csv')
373381

374382
createdFile = storageDir / filename
375383
assert createdFile.exists()
376384
assert createdFile.is_file()
377-
assert createdFile.read_text() == LOREM_IPSUM
385+
assert createdFile.read_text() == CSV_DATA
378386

379387
@pytest.mark.parametrize('content_type', ['bytes', 'text'])
380388
async def test_download_files(
@@ -400,10 +408,10 @@ async def test_download_files(
400408
file_path.write_bytes(base64.b64decode(BASE_64_IMAGE))
401409

402410
case 'text':
403-
filename = 'lorem.txt'
404-
ctype = 'text/plain'
411+
filename = 'data.csv'
412+
ctype = 'text/csv'
405413
file_path = storageDir / filename
406-
file_path.write_text(LOREM_IPSUM)
414+
file_path.write_text(CSV_DATA)
407415

408416
result = await mcp_session.list_resources()
409417

@@ -429,7 +437,99 @@ async def test_download_files(
429437

430438
case 'text':
431439
assert isinstance(resource, types.TextResourceContents)
432-
assert resource.text == LOREM_IPSUM
440+
assert resource.text == CSV_DATA
441+
442+
# Code pieces use hardcoded values of mount
443+
@pytest.mark.parametrize(
444+
'code,expected_output,content_type',
445+
[
446+
pytest.param(
447+
[
448+
'# /// script',
449+
'# dependencies = ["pillow"]',
450+
'# ///',
451+
'from pathlib import Path',
452+
'perm_storage = Path.cwd() / "storage"',
453+
'print(str(perm_storage))',
454+
'assert perm_storage.is_dir()',
455+
'from PIL import Image, ImageFilter',
456+
'img = Image.open("storage/image.png")',
457+
'print(f"Image size: {img.size}")',
458+
'gray_img = img.convert("L")',
459+
'gray_img.save("storage/image-gray.png")',
460+
],
461+
snapshot(""""""),
462+
'bytes',
463+
id='image-transform',
464+
),
465+
pytest.param(
466+
[
467+
'# /// script',
468+
'# dependencies = ["pandas"]',
469+
'# ///',
470+
'import pandas as pd',
471+
'df = pd.read_csv("storage/data.csv")',
472+
'print(df.describe())',
473+
'df["Age_in_10_years"] = df["Age"] + 10',
474+
'df.to_csv("storage/data-processed.csv", index=False)',
475+
],
476+
snapshot(""""""),
477+
'text',
478+
id='dataframe-manipulation',
479+
),
480+
],
481+
)
482+
async def test_run_python_code_with_file(
483+
self,
484+
mcp_session: ClientSession,
485+
server_type: Literal['stdio', 'sse', 'streamable_http'],
486+
mount: bool | str,
487+
code: list[str],
488+
expected_output: str,
489+
content_type: Literal['bytes', 'text'],
490+
tmp_path: Path,
491+
):
492+
if mount is False:
493+
pytest.skip('No directory mounted.')
494+
await mcp_session.initialize()
495+
496+
match content_type:
497+
case 'bytes':
498+
filename = 'image.png'
499+
output_file = 'image-gray.png'
500+
ctype = 'image/png'
501+
data_file = tmp_path / filename
502+
data_file.write_bytes(base64.b64decode(BASE_64_IMAGE))
503+
504+
case 'text':
505+
filename = 'data.csv'
506+
output_file = 'data-processed.csv'
507+
ctype = 'text/csv'
508+
data_file = tmp_path / filename
509+
data_file.write_text(CSV_DATA)
510+
511+
result = await mcp_session.call_tool(
512+
McpTools.UPLOAD_FILE_FROM_URI, {'uri': f'file://{str(data_file)}', 'filename': filename}
513+
)
514+
assert result.isError is False
515+
516+
result = await mcp_session.call_tool(McpTools.RUN_PYTHON_CODE, {'python_code': '\n'.join(code)})
517+
assert result.isError is False
518+
assert len(result.content) == 1
519+
content = result.content[0]
520+
assert isinstance(content, types.TextContent)
521+
assert content.text == expected_output
522+
523+
result = await mcp_session.read_resource(FileUrl(f'file:///{output_file}'))
524+
assert len(result.contents) == 1
525+
resource = result.contents[0]
526+
assert resource.mimeType is not None
527+
assert resource.mimeType.startswith(ctype)
528+
assert (
529+
isinstance(resource, types.BlobResourceContents)
530+
if content_type == 'bytes'
531+
else isinstance(resource, types.TextResourceContents)
532+
)
433533

434534

435535
async def test_install_run_python_code() -> None:

0 commit comments

Comments
 (0)