mcpico 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of mcpico might be problematic. Click here for more details.

Files changed (40) hide show
  1. mcpico-0.1.0/.gitignore +19 -0
  2. mcpico-0.1.0/LICENSE +21 -0
  3. mcpico-0.1.0/PKG-INFO +371 -0
  4. mcpico-0.1.0/README.md +331 -0
  5. mcpico-0.1.0/pyproject.toml +120 -0
  6. mcpico-0.1.0/src/mcpico/__init__.py +22 -0
  7. mcpico-0.1.0/src/mcpico/_client.py +593 -0
  8. mcpico-0.1.0/src/mcpico/_context.py +199 -0
  9. mcpico-0.1.0/src/mcpico/_functions.py +164 -0
  10. mcpico-0.1.0/src/mcpico/_headers.py +140 -0
  11. mcpico-0.1.0/src/mcpico/_jsonrpc.py +111 -0
  12. mcpico-0.1.0/src/mcpico/_legacy.py +234 -0
  13. mcpico-0.1.0/src/mcpico/_schema.py +62 -0
  14. mcpico-0.1.0/src/mcpico/_server.py +975 -0
  15. mcpico-0.1.0/src/mcpico/_state.py +85 -0
  16. mcpico-0.1.0/src/mcpico/_transport.py +119 -0
  17. mcpico-0.1.0/src/mcpico/_uri_template.py +51 -0
  18. mcpico-0.1.0/src/mcpico/auth/__init__.py +148 -0
  19. mcpico-0.1.0/src/mcpico/auth/client.py +535 -0
  20. mcpico-0.1.0/src/mcpico/auth/jwt.py +122 -0
  21. mcpico-0.1.0/src/mcpico/errors.py +115 -0
  22. mcpico-0.1.0/src/mcpico/http/__init__.py +6 -0
  23. mcpico-0.1.0/src/mcpico/http/_client.py +168 -0
  24. mcpico-0.1.0/src/mcpico/http/_granian.py +84 -0
  25. mcpico-0.1.0/src/mcpico/http/_legacy.py +132 -0
  26. mcpico-0.1.0/src/mcpico/http/_server.py +372 -0
  27. mcpico-0.1.0/src/mcpico/py.typed +0 -0
  28. mcpico-0.1.0/src/mcpico/stdio.py +304 -0
  29. mcpico-0.1.0/src/mcpico/types.py +433 -0
  30. mcpico-0.1.0/tests/__init__.py +0 -0
  31. mcpico-0.1.0/tests/conformance/baseline.yml +35 -0
  32. mcpico-0.1.0/tests/conformance/client.py +101 -0
  33. mcpico-0.1.0/tests/conformance/run.py +162 -0
  34. mcpico-0.1.0/tests/conformance/server.py +330 -0
  35. mcpico-0.1.0/tests/stdio_server.py +51 -0
  36. mcpico-0.1.0/tests/test_auth.py +357 -0
  37. mcpico-0.1.0/tests/test_http_live.py +279 -0
  38. mcpico-0.1.0/tests/test_protocol.py +254 -0
  39. mcpico-0.1.0/tests/test_server.py +429 -0
  40. mcpico-0.1.0/tests/test_stdio.py +91 -0
@@ -0,0 +1,19 @@
1
+ # Python-generated files
2
+ __pycache__/
3
+ *.py[oc]
4
+ build/
5
+ dist/
6
+ wheels/
7
+ *.egg-info
8
+
9
+ # Virtual environments
10
+ .venv
11
+
12
+ # Tooling
13
+ .codegraph/
14
+ .pytest_cache/
15
+ .ruff_cache/
16
+ .hypothesis/
17
+
18
+ # Node
19
+ node_modules/
mcpico-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) <year> <copyright holders>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
mcpico-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,371 @@
1
+ Metadata-Version: 2.5
2
+ Name: mcpico
3
+ Version: 0.1.0
4
+ Summary: A lightweight, fully typed Python SDK for the Model Context Protocol
5
+ Project-URL: Repository, https://github.com/antarktier/mcpico
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Keywords: asyncio,json-rpc,llm,mcp,model-context-protocol
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Framework :: AsyncIO
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.12
18
+ Requires-Dist: jsonschema-rs>=0.30
19
+ Requires-Dist: msgspec>=0.19
20
+ Provides-Extra: all
21
+ Requires-Dist: authlib>=1.5; extra == 'all'
22
+ Requires-Dist: granian>=2.2; extra == 'all'
23
+ Requires-Dist: httpx2>=2.16; extra == 'all'
24
+ Requires-Dist: joserfc>=1.0; extra == 'all'
25
+ Requires-Dist: sse-starlette>=2.2; extra == 'all'
26
+ Requires-Dist: starlette>=0.46; extra == 'all'
27
+ Provides-Extra: auth
28
+ Requires-Dist: authlib>=1.5; extra == 'auth'
29
+ Requires-Dist: granian>=2.2; extra == 'auth'
30
+ Requires-Dist: httpx2>=2.16; extra == 'auth'
31
+ Requires-Dist: joserfc>=1.0; extra == 'auth'
32
+ Requires-Dist: sse-starlette>=2.2; extra == 'auth'
33
+ Requires-Dist: starlette>=0.46; extra == 'auth'
34
+ Provides-Extra: http
35
+ Requires-Dist: granian>=2.2; extra == 'http'
36
+ Requires-Dist: httpx2>=2.16; extra == 'http'
37
+ Requires-Dist: sse-starlette>=2.2; extra == 'http'
38
+ Requires-Dist: starlette>=0.46; extra == 'http'
39
+ Description-Content-Type: text/markdown
40
+
41
+ <p align="center">
42
+ <img src="https://raw.githubusercontent.com/antarktier/mcpico/main/docs/public/icon.svg" width="88" height="88" alt="">
43
+ </p>
44
+
45
+ <h1 align="center">MCPico</h1>
46
+
47
+ <p align="center">
48
+ <strong>MCP, made simple.</strong>
49
+ </p>
50
+
51
+ <p align="center">
52
+ <a href="#install">Install</a>&nbsp;&nbsp;&nbsp;
53
+ <a href="https://github.com/antarktier/mcpico/tree/main/docs">Documentation</a>
54
+ </p>
55
+
56
+ ---
57
+
58
+ A small, fully typed Python SDK for the [Model Context Protocol](https://modelcontextprotocol.io):
59
+ client and server, over stdio and Streamable HTTP, with OAuth 2.1. It speaks protocol revision
60
+ **2026-07-28**, and **2025-11-25** for older peers.
61
+
62
+ ```python
63
+ from mcpico import Server
64
+
65
+ server = Server("demo")
66
+
67
+
68
+ @server.tool
69
+ def add(a: int, b: int = 0) -> int:
70
+ """Add two numbers."""
71
+ return a + b
72
+
73
+
74
+ server.run() # stdio; server.run("http", port=8000) for Streamable HTTP
75
+ ```
76
+
77
+ Input and output schemas come from type hints, docstrings become descriptions, and arguments are
78
+ validated before your function runs.
79
+
80
+ ## Install
81
+
82
+ ```console
83
+ pip install mcpico # core and stdio
84
+ pip install "mcpico[http]" # Streamable HTTP (client and server)
85
+ pip install "mcpico[auth]" # OAuth 2.1
86
+ ```
87
+
88
+ With uv:
89
+
90
+ ```console
91
+ uv add mcpico
92
+ uv add "mcpico[http]"
93
+ uv add "mcpico[auth]"
94
+ ```
95
+
96
+ Python 3.12 or newer.
97
+
98
+ ## Servers
99
+
100
+ ### Tools
101
+
102
+ ```python
103
+ from typing import Annotated
104
+
105
+ import msgspec
106
+
107
+ from mcpico import Context, Server
108
+
109
+ server = Server("weather", "1.0", instructions="Forecasts for European cities.")
110
+
111
+
112
+ class Forecast(msgspec.Struct):
113
+ city: str
114
+ celsius: float
115
+
116
+
117
+ @server.tool
118
+ async def forecast(
119
+ city: Annotated[str, msgspec.Meta(description="City name")], ctx: Context
120
+ ) -> Forecast:
121
+ """Tomorrow's forecast."""
122
+ await ctx.report_progress(1, 2, "fetching")
123
+ return Forecast(city, 21.5)
124
+ ```
125
+
126
+ - Parameters annotated with `Context` are injected rather than exposed to clients.
127
+ - Functions returning `str`, content blocks or `None` produce plain content. Anything else is
128
+ structured content, with an output schema derived from the return type.
129
+ - Exceptions become tool errors (`isError: true`) that the model can see.
130
+ - Pass `input_schema=` or `output_schema=` to use hand-written JSON Schemas instead.
131
+
132
+ ### Resources and prompts
133
+
134
+ ```python
135
+ @server.resource("file:///readme.txt", mime_type="text/plain")
136
+ def readme() -> str:
137
+ return "Hello"
138
+
139
+
140
+ @server.resource("users://{user_id}/avatar", mime_type="image/png")
141
+ def avatar(user_id: int) -> bytes: # bytes are sent as a blob
142
+ ...
143
+
144
+
145
+ @server.prompt
146
+ def review(code: str, language: str = "python") -> str:
147
+ """Review some code."""
148
+ return f"Please review this {language} code:\n\n{code}"
149
+ ```
150
+
151
+ URIs containing `{variable}` (one path segment) or `{+variable}` (any text) register templates.
152
+
153
+ ### Asking the user
154
+
155
+ A tool, resource or prompt can ask the client for input. The server holds no session for this:
156
+ it returns the question, and the client retries the request with the answer. The handler then
157
+ runs again from the start, and `elicit` calls that were already answered return their answers.
158
+
159
+ ```python
160
+ class Confirm(msgspec.Struct):
161
+ confirm: bool
162
+
163
+
164
+ @server.tool
165
+ def delete_project(name: str, ctx: Context) -> str:
166
+ answer = ctx.elicit(f"Really delete {name}?", Confirm)
167
+ if answer is None or not answer.confirm: # None: declined or cancelled
168
+ return "Kept."
169
+ ...
170
+ return "Deleted."
171
+ ```
172
+
173
+ The form is derived from the struct or dataclass, whose fields must be strings, numbers,
174
+ booleans or enums (`X | None` makes a field optional). Pass a JSON Schema instead to get the raw
175
+ `ElicitResult`. Code before an `elicit` call can run more than once, so keep side effects after the last one.
176
+ `ctx.elicit_url(...)` sends the user to a URL instead. The state carried between rounds is signed,
177
+ bound to the request and the caller, and expires. Pass `state_secret=` to `Server` when several
178
+ processes serve the same clients.
179
+
180
+ ### Protocol versions
181
+
182
+ A server answers 2026-07-28 and 2025-11-25 clients on the same endpoint, from the same tools,
183
+ resources and prompts. Requests carrying 2026-07-28 metadata are served statelessly; an
184
+ `initialize` request opens a 2025-11-25 session (one per stdio process, or per `Mcp-Session-Id`
185
+ over HTTP), in which `elicit` becomes an `elicitation/create` request to the client.
186
+ `ctx.protocol_version` tells a handler which revision is in use. To serve only some revisions:
187
+
188
+ ```python
189
+ from mcpico.types import LATEST_PROTOCOL_VERSION
190
+
191
+ server = Server("demo", protocol_versions=[LATEST_PROTOCOL_VERSION])
192
+ ```
193
+
194
+ ### Change notifications
195
+
196
+ ```python
197
+ server.add_tool(some_function) # clients listening for tool changes are told
198
+ server.notify_resource_updated("file:///readme.txt")
199
+ ```
200
+
201
+ ### Running
202
+
203
+ ```python
204
+ server.run() # stdio
205
+ server.run("http", host="127.0.0.1", port=8000) # Streamable HTTP, on Granian
206
+ ```
207
+
208
+ Inside an existing event loop, use `await server.serve(...)` and cancel the task to stop. The HTTP
209
+ server shuts down gracefully: it ends open subscription streams and finishes in-flight requests.
210
+ `mcpico.http.serve_async` also takes `ready=` (an `asyncio.Event` set once the server accepts
211
+ connections) and `ssl_cert`/`ssl_key` for HTTPS.
212
+
213
+ For other deployments, `create_app` returns a standard ASGI application:
214
+
215
+ ```python
216
+ from mcpico.http import create_app
217
+
218
+ app = create_app(server, allowed_origins=["https://app.example.com"])
219
+ ```
220
+
221
+ ```console
222
+ granian --interface asgi --workers 4 myserver:app
223
+ ```
224
+
225
+ Requests are independent, so workers share nothing but a common `state_secret`. Change
226
+ notifications reach only subscribers connected to the same process. 2025-11-25 sessions live in
227
+ the process that opened them: route them by `Mcp-Session-Id`, or serve only 2026-07-28.
228
+ Browser requests from origins other than localhost are rejected unless listed in
229
+ `allowed_origins`.
230
+
231
+ ## Clients
232
+
233
+ ```python
234
+ import asyncio
235
+
236
+ from mcpico import Client, StdioTransport
237
+
238
+
239
+ async def main() -> None:
240
+ async with Client(StdioTransport("python", ["server.py"])) as client:
241
+ tools = await client.list_tools()
242
+ result = await client.call_tool("add", {"a": 1, "b": 2})
243
+ print(result.parse(int))
244
+
245
+
246
+ asyncio.run(main())
247
+ ```
248
+
249
+ ### Transports
250
+
251
+ `StdioTransport` starts the server as a subprocess; the command and arguments may be paths.
252
+ Over Streamable HTTP:
253
+
254
+ ```python
255
+ from mcpico.http import HttpTransport
256
+
257
+ client = Client(HttpTransport("https://mcp.example.com/mcp"))
258
+ ```
259
+
260
+ ### Results
261
+
262
+ ```python
263
+ result = await client.call_tool("weather", {"city": "Oslo"})
264
+ weather = result.parse(Weather) # structured content; raises ToolError if the tool failed
265
+ print(result.text) # the text blocks, joined
266
+
267
+ note = await client.read_resource("notes://todo")
268
+ print(note.text) # or note.data for binary contents
269
+ ```
270
+
271
+ Structured content is checked against the tool's output schema, and `list_*` methods follow
272
+ pagination.
273
+
274
+ ### Questions, progress and timeouts
275
+
276
+ ```python
277
+ from mcpico.types import ElicitRequest, ElicitResult
278
+
279
+
280
+ async def ask(request: ElicitRequest) -> ElicitResult:
281
+ print(request.message)
282
+ return ElicitResult(action="accept", content={"confirm": True})
283
+
284
+
285
+ async with Client(transport, elicitation=ask) as client:
286
+ await client.call_tool("delete_project", {"name": "old"}, timeout=30, progress=print)
287
+ ```
288
+
289
+ A timeout or a cancelled task also cancels the request on the server.
290
+
291
+ ### Change notifications
292
+
293
+ ```python
294
+ async with client.listen(tools=True) as subscription:
295
+ async for notification in subscription:
296
+ print(notification.method)
297
+ ```
298
+
299
+ ### Protocol versions
300
+
301
+ The client speaks 2026-07-28 first. When a server does not understand it, the client falls back
302
+ to a 2025-11-25 `initialize` session, with the same API.
303
+
304
+ - `Client(..., protocol_versions=[...])` restricts the versions it may use.
305
+ - A custom transport implements `SessionTransport` to support the fallback.
306
+
307
+ ## Authorization
308
+
309
+ A server checks bearer tokens and publishes its Protected Resource Metadata:
310
+
311
+ ```python
312
+ from mcpico.auth import ProtectedResource
313
+
314
+ auth = ProtectedResource.jwt(
315
+ "https://mcp.example.com/mcp",
316
+ issuer="https://auth.example.com",
317
+ jwks_uri="https://auth.example.com/.well-known/jwks.json",
318
+ required_scopes=("mcp",),
319
+ )
320
+ server.run("http", host="0.0.0.0", port=8000, auth=auth)
321
+ ```
322
+
323
+ Handlers read the validated token from `ctx.access_token`, and can raise
324
+ `InsufficientScopeError(["admin"])` to ask the client to step up. Implement `TokenVerifier` to
325
+ validate tokens some other way, such as introspection, and pass it to `ProtectedResource(...)`.
326
+
327
+ A client uses `OAuth`, an `httpx2.Auth`. It discovers the authorization server, runs the
328
+ authorization code flow with PKCE, and refreshes tokens:
329
+
330
+ ```python
331
+ from mcpico.auth.client import ClientCredentials, LoopbackBrowser, OAuth
332
+
333
+ browser = LoopbackBrowser(8765) # opens the system browser, listens for the redirect
334
+ oauth = OAuth(
335
+ authorize=browser,
336
+ redirect_uri=browser.redirect_uri,
337
+ credentials={"https://auth.example.com": ClientCredentials("my-client-id")},
338
+ )
339
+ client = Client(HttpTransport("https://mcp.example.com/mcp", auth=oauth))
340
+ ```
341
+
342
+ `authorize` can be any async function that sends the user to a URL and returns the URL they were
343
+ redirected to. Without it, the client credentials grant is used. Instead of pre-registered credentials,
344
+ `client_metadata_url=` identifies the client with a Client ID Metadata Document.
345
+
346
+ ## Scope
347
+
348
+ MCPico implements the current protocol revision, and revision 2025-11-25 for clients and servers
349
+ that do not speak it yet. Features the specification deprecates or removed are not provided in
350
+ either: roots, sampling, logging and dynamic client registration. With 2025-11-25 peers,
351
+ `Client.listen` is unavailable and HTTP sessions are not resumable.
352
+
353
+ ## Development
354
+
355
+ ```console
356
+ uv sync --all-extras
357
+ uv run ruff format --check .
358
+ uv run ruff check .
359
+ uv run pyright
360
+ uv run mypy
361
+ uv run pyrefly check
362
+ uv run ty check # advisory
363
+ uv run pytest
364
+ ```
365
+
366
+ The documentation site, with an API reference generated from the docstrings, is in
367
+ [`docs/`](https://github.com/antarktier/mcpico/tree/main/docs).
368
+
369
+ ## License
370
+
371
+ MIT