Skip to content

Commit 4cbf815

Browse files
committed
Initial import
0 parents  commit 4cbf815

33 files changed

+2986
-0
lines changed

.devcontainer/devcontainer.json

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// For format details, see https://aka.ms/devcontainer.json. For config options, see the
2+
// README at: https://github.com/devcontainers/templates/tree/main/src/python
3+
{
4+
"name": "Python 3",
5+
// Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
6+
"image": "mcr.microsoft.com/devcontainers/python:1-3.12-bookworm"
7+
8+
// Features to add to the dev container. More info: https://containers.dev/features.
9+
// "features": {},
10+
11+
// Use 'forwardPorts' to make a list of ports inside the container available locally.
12+
// "forwardPorts": [],
13+
14+
// Use 'postCreateCommand' to run commands after the container is created.
15+
// "postCreateCommand": "pip3 install --user -r requirements.txt",
16+
17+
// Configure tool-specific properties.
18+
// "customizations": {},
19+
20+
// Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
21+
// "remoteUser": "root"
22+
}

.gitignore

Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
# Byte-compiled / optimized / DLL files
2+
__pycache__/
3+
*.py[cod]
4+
*$py.class
5+
6+
# C extensions
7+
*.so
8+
9+
# Distribution / packaging
10+
.Python
11+
build/
12+
develop-eggs/
13+
dist/
14+
downloads/
15+
eggs/
16+
.eggs/
17+
lib/
18+
lib64/
19+
parts/
20+
sdist/
21+
var/
22+
wheels/
23+
share/python-wheels/
24+
*.egg-info/
25+
.installed.cfg
26+
*.egg
27+
MANIFEST
28+
29+
# PyInstaller
30+
# Usually these files are written by a python script from a template
31+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
32+
*.manifest
33+
*.spec
34+
35+
# Installer logs
36+
pip-log.txt
37+
pip-delete-this-directory.txt
38+
39+
# Unit test / coverage reports
40+
htmlcov/
41+
.tox/
42+
.nox/
43+
.coverage
44+
.coverage.*
45+
.cache
46+
nosetests.xml
47+
coverage.xml
48+
*.cover
49+
*.py,cover
50+
.hypothesis/
51+
.pytest_cache/
52+
cover/
53+
54+
# Translations
55+
*.mo
56+
*.pot
57+
58+
# Django stuff:
59+
*.log
60+
local_settings.py
61+
db.sqlite3
62+
db.sqlite3-journal
63+
64+
# Flask stuff:
65+
instance/
66+
.webassets-cache
67+
68+
# Scrapy stuff:
69+
.scrapy
70+
71+
# Sphinx documentation
72+
docs/_build/
73+
74+
# PyBuilder
75+
.pybuilder/
76+
target/
77+
78+
# Jupyter Notebook
79+
.ipynb_checkpoints
80+
81+
# IPython
82+
profile_default/
83+
ipython_config.py
84+
85+
# pyenv
86+
# For a library or package, you might want to ignore these files since the code is
87+
# intended to run in multiple environments; otherwise, check them in:
88+
# .python-version
89+
90+
# pipenv
91+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
93+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
94+
# install all needed dependencies.
95+
#Pipfile.lock
96+
97+
# poetry
98+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99+
# This is especially recommended for binary packages to ensure reproducibility, and is more
100+
# commonly ignored for libraries.
101+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102+
#poetry.lock
103+
104+
# pdm
105+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106+
#pdm.lock
107+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108+
# in version control.
109+
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110+
.pdm.toml
111+
.pdm-python
112+
.pdm-build/
113+
114+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115+
__pypackages__/
116+
117+
# Celery stuff
118+
celerybeat-schedule
119+
celerybeat.pid
120+
121+
# SageMath parsed files
122+
*.sage.py
123+
124+
# Environments
125+
.env
126+
.venv
127+
env/
128+
venv/
129+
ENV/
130+
env.bak/
131+
venv.bak/
132+
133+
# Spyder project settings
134+
.spyderproject
135+
.spyproject
136+
137+
# Rope project settings
138+
.ropeproject
139+
140+
# mkdocs documentation
141+
/site
142+
143+
# mypy
144+
.mypy_cache/
145+
.dmypy.json
146+
dmypy.json
147+
148+
# Pyre type checker
149+
.pyre/
150+
151+
# pytype static type analyzer
152+
.pytype/
153+
154+
# Cython debug symbols
155+
cython_debug/
156+
157+
# PyCharm
158+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160+
# and can be added to the global gitignore or merged into this file. For a more nuclear
161+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
162+
#.idea/

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# mcp-python
2+
Model Context Protocol implementation for Python

mcp_python/__init__.py

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
from .client.session import ClientSession
2+
from .client.stdio import StdioServerParameters, stdio_client
3+
from .server.session import ServerSession
4+
from .server.stdio import stdio_server
5+
from .shared.exceptions import McpError
6+
from .types import (
7+
CallToolRequest,
8+
ClientCapabilities,
9+
ClientNotification,
10+
ClientRequest,
11+
ClientResult,
12+
CompleteRequest,
13+
CreateMessageRequest,
14+
CreateMessageResult,
15+
ErrorData,
16+
GetPromptRequest,
17+
GetPromptResult,
18+
Implementation,
19+
IncludeContext,
20+
InitializedNotification,
21+
InitializeRequest,
22+
InitializeResult,
23+
JSONRPCError,
24+
JSONRPCRequest,
25+
JSONRPCResponse,
26+
ListPromptsRequest,
27+
ListPromptsResult,
28+
ListResourcesRequest,
29+
ListResourcesResult,
30+
ListToolsResult,
31+
LoggingLevel,
32+
LoggingMessageNotification,
33+
Notification,
34+
PingRequest,
35+
ProgressNotification,
36+
ReadResourceRequest,
37+
ReadResourceResult,
38+
Resource,
39+
ResourceUpdatedNotification,
40+
Role as SamplingRole,
41+
SamplingMessage,
42+
ServerCapabilities,
43+
ServerNotification,
44+
ServerRequest,
45+
ServerResult,
46+
SetLevelRequest,
47+
StopReason,
48+
SubscribeRequest,
49+
Tool,
50+
UnsubscribeRequest,
51+
)
52+
53+
__all__ = [
54+
"CallToolRequest",
55+
"ClientCapabilities",
56+
"ClientNotification",
57+
"ClientRequest",
58+
"ClientResult",
59+
"ClientSession",
60+
"CreateMessageRequest",
61+
"CreateMessageResult",
62+
"ErrorData",
63+
"GetPromptRequest",
64+
"GetPromptResult",
65+
"Implementation",
66+
"IncludeContext",
67+
"InitializeRequest",
68+
"InitializeResult",
69+
"InitializedNotification",
70+
"JSONRPCError",
71+
"JSONRPCRequest",
72+
"ListPromptsRequest",
73+
"ListPromptsResult",
74+
"ListResourcesRequest",
75+
"ListResourcesResult",
76+
"ListToolsResult",
77+
"LoggingLevel",
78+
"LoggingMessageNotification",
79+
"McpError",
80+
"Notification",
81+
"PingRequest",
82+
"ProgressNotification",
83+
"ReadResourceRequest",
84+
"ReadResourceResult",
85+
"ResourceUpdatedNotification",
86+
"Resource",
87+
"SamplingMessage",
88+
"SamplingRole",
89+
"ServerCapabilities",
90+
"ServerNotification",
91+
"ServerRequest",
92+
"ServerResult",
93+
"ServerSession",
94+
"SetLevelRequest",
95+
"StdioServerParameters",
96+
"StopReason",
97+
"SubscribeRequest",
98+
"Tool",
99+
"UnsubscribeRequest",
100+
"stdio_client",
101+
"stdio_server",
102+
"CompleteRequest",
103+
"JSONRPCResponse",
104+
]

mcp_python/client/__init__.py

Whitespace-only changes.

mcp_python/client/__main__.py

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import logging
2+
import sys
3+
from functools import partial
4+
from urllib.parse import urlparse
5+
6+
import anyio
7+
import click
8+
9+
from mcp_python.client.session import ClientSession
10+
from mcp_python.client.sse import sse_client
11+
from mcp_python.client.stdio import StdioServerParameters, stdio_client
12+
13+
if not sys.warnoptions:
14+
import warnings
15+
16+
warnings.simplefilter("ignore")
17+
18+
logging.basicConfig(level=logging.INFO)
19+
logger = logging.getLogger("client")
20+
21+
22+
async def receive_loop(session: ClientSession):
23+
logger.info("Starting receive loop")
24+
async for message in session.incoming_messages:
25+
if isinstance(message, Exception):
26+
logger.error("Error: %s", message)
27+
continue
28+
29+
logger.info("Received message from server: %s", message)
30+
31+
32+
async def run_session(read_stream, write_stream):
33+
async with (
34+
ClientSession(read_stream, write_stream) as session,
35+
anyio.create_task_group() as tg,
36+
):
37+
tg.start_soon(receive_loop, session)
38+
39+
logger.info("Initializing session")
40+
await session.initialize()
41+
logger.info("Initialized")
42+
43+
44+
async def main(command_or_url: str, args: list[str], env: list[tuple[str, str]]):
45+
env_dict = dict(env)
46+
47+
if urlparse(command_or_url).scheme in ("http", "https"):
48+
# Use SSE client for HTTP(S) URLs
49+
async with sse_client(command_or_url) as streams:
50+
await run_session(*streams)
51+
else:
52+
# Use stdio client for commands
53+
server_parameters = StdioServerParameters(
54+
command=command_or_url, args=args, env=env_dict
55+
)
56+
async with stdio_client(server_parameters) as streams:
57+
await run_session(*streams)
58+
59+
60+
@click.command()
61+
@click.argument("command_or_url")
62+
@click.argument("args", nargs=-1)
63+
@click.option(
64+
"--env",
65+
"-e",
66+
multiple=True,
67+
nargs=2,
68+
metavar="KEY VALUE",
69+
help="Environment variables to set. Can be used multiple times.",
70+
)
71+
def cli(*args, **kwargs):
72+
anyio.run(partial(main, *args, **kwargs), backend="trio")
73+
74+
75+
if __name__ == "__main__":
76+
cli()

0 commit comments

Comments
 (0)