partiful-api-mcp 1.0.2__py3-none-any.whl
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.
- partiful_api_mcp/__init__.py +28 -0
- partiful_api_mcp/api.py +213 -0
- partiful_api_mcp/app.py +37 -0
- partiful_api_mcp/cli.py +192 -0
- partiful_api_mcp/core/__init__.py +0 -0
- partiful_api_mcp/core/account_guard.py +35 -0
- partiful_api_mcp/core/context.py +191 -0
- partiful_api_mcp/core/errors.py +78 -0
- partiful_api_mcp/core/helpers.py +33 -0
- partiful_api_mcp/core/tools.py +106 -0
- partiful_api_mcp/mcp_context.py +126 -0
- partiful_api_mcp/mcp_server.py +67 -0
- partiful_api_mcp/partiful/__init__.py +0 -0
- partiful_api_mcp/partiful/auth.py +22 -0
- partiful_api_mcp/partiful/client.py +118 -0
- partiful_api_mcp/partiful/editing.py +123 -0
- partiful_api_mcp/partiful/events.py +158 -0
- partiful_api_mcp/partiful/firestore.py +135 -0
- partiful_api_mcp/partiful/guests.py +77 -0
- partiful_api_mcp/partiful/tools/__init__.py +0 -0
- partiful_api_mcp/partiful/tools/approve_guests.py +79 -0
- partiful_api_mcp/partiful/tools/cancel_event.py +69 -0
- partiful_api_mcp/partiful/tools/check_in_guests.py +64 -0
- partiful_api_mcp/partiful/tools/create_event.py +96 -0
- partiful_api_mcp/partiful/tools/delete_event.py +49 -0
- partiful_api_mcp/partiful/tools/duplicate_event.py +83 -0
- partiful_api_mcp/partiful/tools/export_guest_list.py +83 -0
- partiful_api_mcp/partiful/tools/get_event.py +60 -0
- partiful_api_mcp/partiful/tools/invite_guests.py +107 -0
- partiful_api_mcp/partiful/tools/list_events.py +81 -0
- partiful_api_mcp/partiful/tools/list_guests.py +81 -0
- partiful_api_mcp/partiful/tools/list_past_guests.py +115 -0
- partiful_api_mcp/partiful/tools/send_text_blast.py +100 -0
- partiful_api_mcp/partiful/tools/update_event.py +50 -0
- partiful_api_mcp/runner.py +117 -0
- partiful_api_mcp/scripting.py +73 -0
- partiful_api_mcp/session.py +275 -0
- partiful_api_mcp-1.0.2.dist-info/METADATA +422 -0
- partiful_api_mcp-1.0.2.dist-info/RECORD +42 -0
- partiful_api_mcp-1.0.2.dist-info/WHEEL +4 -0
- partiful_api_mcp-1.0.2.dist-info/entry_points.txt +3 -0
- partiful_api_mcp-1.0.2.dist-info/licenses/LICENSE +133 -0
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Self-hosted API and MCP server for one app (see app.py). Personal use only, see LICENSE.
|
|
2
|
+
|
|
3
|
+
From Python, without a server:
|
|
4
|
+
|
|
5
|
+
from partiful_api_mcp import call
|
|
6
|
+
events = call("list_events")["events"]
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
__version__ = "1.0.2"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def call(tool: str, args: dict[str, Any] | None = None, **kwargs: Any) -> Any:
|
|
18
|
+
"""Run one tool with the saved session and return its answer. Raises ToolError on failure."""
|
|
19
|
+
from partiful_api_mcp.runner import Runner
|
|
20
|
+
|
|
21
|
+
async def go() -> Any:
|
|
22
|
+
runner = Runner()
|
|
23
|
+
try:
|
|
24
|
+
return await runner.run(tool, {**(args or {}), **kwargs})
|
|
25
|
+
finally:
|
|
26
|
+
await runner.close()
|
|
27
|
+
|
|
28
|
+
return asyncio.run(go())
|
partiful_api_mcp/api.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""The REST API and the MCP endpoint on one port.
|
|
2
|
+
|
|
3
|
+
- `GET|POST|PUT|PATCH|DELETE <app.API_PREFIX>/<route>`: each tool at its route, the same paths as the
|
|
4
|
+
hosted API at cotlet.dev. Path parts and the query string are arguments; a JSON body adds the rest.
|
|
5
|
+
- `POST <app.API_PREFIX>/tools/{name}`: any tool by name, the JSON body is its arguments.
|
|
6
|
+
- `GET <app.API_PREFIX>/tools`: every tool with its schema. OpenAPI at `/docs` and `/openapi.json`.
|
|
7
|
+
- `/mcp`: the MCP server over streamable HTTP.
|
|
8
|
+
|
|
9
|
+
With <ENV>_MCP_TOKEN set, every request needs `Authorization: Bearer <token>`.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import contextlib
|
|
15
|
+
import hmac
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
from collections.abc import AsyncIterator, Awaitable, Callable
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from fastapi import FastAPI, Request
|
|
23
|
+
from fastapi.responses import JSONResponse
|
|
24
|
+
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
|
|
25
|
+
|
|
26
|
+
from partiful_api_mcp import __version__, app, mcp_server
|
|
27
|
+
from partiful_api_mcp.core.errors import HTTP_STATUS, ErrorCode, ToolError
|
|
28
|
+
from partiful_api_mcp.core.tools import ToolSpec
|
|
29
|
+
from partiful_api_mcp.runner import Runner, description, tools
|
|
30
|
+
|
|
31
|
+
PREFIX = app.API_PREFIX
|
|
32
|
+
ASGI = Callable[[dict[str, Any], Callable[[], Awaitable[Any]], Callable[[Any], Awaitable[None]]], Awaitable[None]]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _error(code: ErrorCode, message: str) -> JSONResponse:
|
|
36
|
+
return JSONResponse({"error": code.value, "message": message}, status_code=HTTP_STATUS.get(code, 500))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _typed(value: str, schema: dict[str, Any]) -> Any:
|
|
40
|
+
kind = schema.get("type")
|
|
41
|
+
try:
|
|
42
|
+
if kind == "integer":
|
|
43
|
+
return int(value)
|
|
44
|
+
if kind == "number":
|
|
45
|
+
return float(value)
|
|
46
|
+
except ValueError:
|
|
47
|
+
return value
|
|
48
|
+
if kind == "boolean":
|
|
49
|
+
return value.lower() in ("1", "true", "yes", "on")
|
|
50
|
+
if kind == "array":
|
|
51
|
+
return [_typed(v, schema.get("items") or {}) for v in value.split(",") if v]
|
|
52
|
+
if kind == "object":
|
|
53
|
+
with contextlib.suppress(ValueError):
|
|
54
|
+
return json.loads(value)
|
|
55
|
+
return value
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _route_order(spec: ToolSpec) -> list[int]:
|
|
59
|
+
"""Literal segments before {placeholders}, so /groups/discover wins over /groups/{group}."""
|
|
60
|
+
path = (spec.route or "").split(" ", 1)[1]
|
|
61
|
+
return [1 if part.startswith("{") else 0 for part in path.strip("/").split("/")]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _tag(path: str) -> str:
|
|
65
|
+
"""OpenAPI group: the part after /groups/{group}/ (posts, members ...), else the first part."""
|
|
66
|
+
parts = path.strip("/").split("/")
|
|
67
|
+
return parts[2] if parts[:2] == ["groups", "{group}"] and len(parts) > 2 else parts[0]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _openapi(spec: ToolSpec, method: str, path: str) -> dict[str, Any]:
|
|
71
|
+
props: dict[str, Any] = spec.input_schema.get("properties") or {}
|
|
72
|
+
required = set(spec.input_schema.get("required") or [])
|
|
73
|
+
in_path = set(re.findall(r"\{(\w+)\}", path))
|
|
74
|
+
parameters = [
|
|
75
|
+
{"name": name, "in": "path", "required": True, "schema": props.get(name, {"type": "string"})}
|
|
76
|
+
for name in in_path
|
|
77
|
+
]
|
|
78
|
+
rest = {k: v for k, v in props.items() if k not in in_path}
|
|
79
|
+
extra: dict[str, Any] = {}
|
|
80
|
+
if method == "GET":
|
|
81
|
+
parameters += [
|
|
82
|
+
{"name": name, "in": "query", "required": name in required, "schema": schema}
|
|
83
|
+
for name, schema in rest.items()
|
|
84
|
+
]
|
|
85
|
+
elif rest:
|
|
86
|
+
body = {"type": "object", "properties": rest, "required": sorted(required - in_path)}
|
|
87
|
+
extra["requestBody"] = {"required": bool(body["required"]), "content": {"application/json": {"schema": body}}}
|
|
88
|
+
if spec.example_response:
|
|
89
|
+
extra["responses"] = {
|
|
90
|
+
"200": {"description": "OK", "content": {"application/json": {"example": spec.example_response}}}
|
|
91
|
+
}
|
|
92
|
+
return {"parameters": parameters, **extra}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
async def _arguments(request: Request, spec: ToolSpec) -> dict[str, Any]:
|
|
96
|
+
props: dict[str, Any] = spec.input_schema.get("properties") or {}
|
|
97
|
+
args: dict[str, Any] = {}
|
|
98
|
+
if request.method != "GET":
|
|
99
|
+
raw = await request.body()
|
|
100
|
+
if raw.strip():
|
|
101
|
+
try:
|
|
102
|
+
body = json.loads(raw)
|
|
103
|
+
except ValueError:
|
|
104
|
+
raise ToolError("The body must be a JSON object.", ErrorCode.INVALID_INPUT) from None
|
|
105
|
+
if not isinstance(body, dict):
|
|
106
|
+
raise ToolError("The body must be a JSON object.", ErrorCode.INVALID_INPUT)
|
|
107
|
+
args.update(body)
|
|
108
|
+
for name in request.query_params:
|
|
109
|
+
values = request.query_params.getlist(name)
|
|
110
|
+
schema = props.get(name) or {}
|
|
111
|
+
args[name] = (
|
|
112
|
+
[_typed(v, schema.get("items") or {}) for v in values]
|
|
113
|
+
if schema.get("type") == "array" and len(values) > 1
|
|
114
|
+
else _typed(values[-1], schema)
|
|
115
|
+
)
|
|
116
|
+
for name, value in request.path_params.items():
|
|
117
|
+
args[name] = _typed(value, props.get(name) or {})
|
|
118
|
+
return args
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def create_app(runner: Runner) -> ASGI:
|
|
122
|
+
manager = StreamableHTTPSessionManager(app=mcp_server.build(runner), json_response=True, stateless=True)
|
|
123
|
+
token = os.environ.get(f"{app.ENV}_MCP_TOKEN", "").strip()
|
|
124
|
+
|
|
125
|
+
@contextlib.asynccontextmanager
|
|
126
|
+
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
|
|
127
|
+
async with manager.run():
|
|
128
|
+
yield
|
|
129
|
+
await runner.close()
|
|
130
|
+
|
|
131
|
+
api = FastAPI(
|
|
132
|
+
title=f"{app.NAME} API (self-hosted)",
|
|
133
|
+
version=__version__,
|
|
134
|
+
description=f"Your {app.NAME} account as a REST API, run on your machine with your Chrome's session.",
|
|
135
|
+
lifespan=lifespan,
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
async def call(spec: ToolSpec, args: dict[str, Any]) -> JSONResponse:
|
|
139
|
+
try:
|
|
140
|
+
result = await runner.run(spec.name, args)
|
|
141
|
+
except ToolError as exc:
|
|
142
|
+
return _error(exc.code, str(exc))
|
|
143
|
+
return JSONResponse(result)
|
|
144
|
+
|
|
145
|
+
def endpoint(spec: ToolSpec) -> Callable[[Request], Awaitable[JSONResponse]]:
|
|
146
|
+
async def handle(request: Request) -> JSONResponse:
|
|
147
|
+
try:
|
|
148
|
+
args = await _arguments(request, spec)
|
|
149
|
+
except ToolError as exc:
|
|
150
|
+
return _error(exc.code, str(exc))
|
|
151
|
+
return await call(spec, args)
|
|
152
|
+
|
|
153
|
+
return handle
|
|
154
|
+
|
|
155
|
+
@api.get(f"{PREFIX}/tools", summary="Every tool with its route and input schema")
|
|
156
|
+
async def list_tools() -> list[dict[str, Any]]:
|
|
157
|
+
return [
|
|
158
|
+
{
|
|
159
|
+
"name": spec.name,
|
|
160
|
+
"title": spec.title,
|
|
161
|
+
"access": spec.access,
|
|
162
|
+
"route": spec.route,
|
|
163
|
+
"description": description(spec),
|
|
164
|
+
"input_schema": spec.input_schema,
|
|
165
|
+
"example_response": spec.example_response,
|
|
166
|
+
}
|
|
167
|
+
for spec in tools(runner.read_only)
|
|
168
|
+
]
|
|
169
|
+
|
|
170
|
+
@api.post(f"{PREFIX}/tools/{{name}}", summary="Call any tool by name; the JSON body is its arguments")
|
|
171
|
+
async def call_by_name(name: str, request: Request) -> JSONResponse:
|
|
172
|
+
raw = await request.body()
|
|
173
|
+
try:
|
|
174
|
+
args = json.loads(raw) if raw.strip() else {}
|
|
175
|
+
except ValueError:
|
|
176
|
+
return _error(ErrorCode.INVALID_INPUT, "The body must be a JSON object.")
|
|
177
|
+
if not isinstance(args, dict):
|
|
178
|
+
return _error(ErrorCode.INVALID_INPUT, "The body must be a JSON object.")
|
|
179
|
+
spec = next((s for s in tools() if s.name == name), None)
|
|
180
|
+
if spec is None:
|
|
181
|
+
return _error(ErrorCode.UNKNOWN_TOOL, f"No tool '{name}'. GET {PREFIX}/tools lists them.")
|
|
182
|
+
return await call(spec, args)
|
|
183
|
+
|
|
184
|
+
for spec in sorted(tools(runner.read_only), key=_route_order):
|
|
185
|
+
method, path = (spec.route or "").split(" ", 1)
|
|
186
|
+
api.add_api_route(
|
|
187
|
+
PREFIX + path,
|
|
188
|
+
endpoint(spec),
|
|
189
|
+
methods=[method],
|
|
190
|
+
name=spec.name,
|
|
191
|
+
operation_id=spec.name,
|
|
192
|
+
summary=spec.title,
|
|
193
|
+
description=description(spec),
|
|
194
|
+
tags=[_tag(path)],
|
|
195
|
+
openapi_extra=_openapi(spec, method, path),
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
async def asgi(
|
|
199
|
+
scope: dict[str, Any], receive: Callable[[], Awaitable[Any]], send: Callable[[Any], Awaitable[None]]
|
|
200
|
+
) -> None:
|
|
201
|
+
if scope["type"] == "http" and token:
|
|
202
|
+
sent = dict(scope.get("headers") or []).get(b"authorization", b"").decode()
|
|
203
|
+
if not hmac.compare_digest(sent, f"Bearer {token}"):
|
|
204
|
+
await _error(ErrorCode.AUTH_REQUIRED, f"Send Authorization: Bearer <{app.ENV}_MCP_TOKEN>.")(
|
|
205
|
+
scope, receive, send
|
|
206
|
+
)
|
|
207
|
+
return
|
|
208
|
+
if scope["type"] == "http" and (scope["path"] == "/mcp" or scope["path"].startswith("/mcp/")):
|
|
209
|
+
await manager.handle_request(scope, receive, send)
|
|
210
|
+
return
|
|
211
|
+
await api(scope, receive, send)
|
|
212
|
+
|
|
213
|
+
return asgi
|
partiful_api_mcp/app.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Everything the server knows about Partiful outside `partiful/`: names, domains and where the session lives.
|
|
2
|
+
|
|
3
|
+
The rest of the package reads these values and never names the app itself.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
NAME = "Partiful"
|
|
9
|
+
SLUG = "partiful"
|
|
10
|
+
# The command and the prefix of every environment variable (PARTIFUL_MCP_HOME, PARTIFUL_MCP_TOKEN ...).
|
|
11
|
+
CLI = "partiful-mcp"
|
|
12
|
+
ENV = "PARTIFUL"
|
|
13
|
+
# Requests may reach only these hosts and their subdomains. Their cookies are read from Chrome.
|
|
14
|
+
# securetoken.googleapis.com renews the sign-in token, firestore.googleapis.com holds guest lists and event edits.
|
|
15
|
+
DOMAINS = ("partiful.com", "securetoken.googleapis.com", "firestore.googleapis.com")
|
|
16
|
+
# Present only while signed in.
|
|
17
|
+
SESSION_COOKIES = ("_partiful_session",)
|
|
18
|
+
LOGIN_URL = "https://partiful.com/login"
|
|
19
|
+
# A final URL with one of these means the app signed the session out.
|
|
20
|
+
LOGGED_OUT_MARKERS = ("/login",)
|
|
21
|
+
# The web app keeps the signed-in user (Firebase, with its refresh token) in this origin's IndexedDB.
|
|
22
|
+
# `connect` reads these keys from a tab of the origin; without them the session is not signed in.
|
|
23
|
+
STORAGE_ORIGIN = "https://partiful.com"
|
|
24
|
+
STORAGE_PAGE = "https://partiful.com/events"
|
|
25
|
+
STORAGE_KEYS = ("firebase:authUser:AIzaSyCky6PJ7cHRdBKk5X7gjuWERWaKWBHr4_k:[DEFAULT]",)
|
|
26
|
+
# A 401 or 403 whose body has one of these asks for a fresh sign-in. Partiful has none.
|
|
27
|
+
RELOGIN_MARKERS: tuple[str, ...] = ()
|
|
28
|
+
# Paths of the app's sign-in, sign-out and the user's own record: tools may read them, never write to them.
|
|
29
|
+
ACCOUNT_PATHS = (
|
|
30
|
+
r"^/api/(login|logout)$",
|
|
31
|
+
r"^/(sendAuthCode|sendAuthCodeTrusted|getLoginToken|setConsentMetadata)$",
|
|
32
|
+
r"^/(updateUser|deleteUser|deactivateUser|updateUserReference)$",
|
|
33
|
+
)
|
|
34
|
+
# REST routes live under this path, the same as on cotlet.dev.
|
|
35
|
+
API_PREFIX = "/api/v1/partiful"
|
|
36
|
+
# Prepended to the MCP server's instructions: where an agent starts.
|
|
37
|
+
AGENT_START = "Start with list_events: its `event_id` values are what every other tool takes."
|
partiful_api_mcp/cli.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""<cli>: connect your Chrome, then run the REST API and MCP server, or call one tool.
|
|
2
|
+
|
|
3
|
+
<cli> connect # read your session of the app from Chrome (remote debugging on)
|
|
4
|
+
<cli> status # which account the saved session is
|
|
5
|
+
<cli> tools # every tool, read or write
|
|
6
|
+
<cli> call <tool> k=v # one tool, arguments as JSON or key=value
|
|
7
|
+
<cli> mcp # MCP server over stdio, for Claude Code, Claude Desktop, Cursor
|
|
8
|
+
<cli> serve # REST API + MCP over HTTP on http://127.0.0.1:8787
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import argparse
|
|
14
|
+
import asyncio
|
|
15
|
+
import ipaddress
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import sys
|
|
19
|
+
from typing import Any
|
|
20
|
+
from urllib.parse import urlsplit
|
|
21
|
+
|
|
22
|
+
from partiful_api_mcp import __version__, app
|
|
23
|
+
from partiful_api_mcp import session as sessions
|
|
24
|
+
from partiful_api_mcp.core.errors import ToolError
|
|
25
|
+
from partiful_api_mcp.runner import Runner, all_tools, tools
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _connect(args: argparse.Namespace) -> None:
|
|
29
|
+
if not args.cdp:
|
|
30
|
+
print("Connecting to Chrome. Click Allow if Chrome asks about remote debugging.", file=sys.stderr)
|
|
31
|
+
session = sessions.from_chrome(args.cdp, args.profile_dir)
|
|
32
|
+
path = sessions.save(session)
|
|
33
|
+
who = asyncio.run(_whoami())
|
|
34
|
+
print(
|
|
35
|
+
f"Saved {len(session.cookies)} {app.NAME} cookies and {sum(map(len, session.local_storage.values()))} sign-in keys to {path}"
|
|
36
|
+
)
|
|
37
|
+
print(f"Signed in to {app.NAME} as {who}" if who else f"Saved, but {app.NAME} did not confirm the session.")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
async def _whoami() -> str | None:
|
|
41
|
+
from partiful_api_mcp.core.context import ToolContext
|
|
42
|
+
from partiful_api_mcp.partiful.auth import whoami
|
|
43
|
+
|
|
44
|
+
ctx = ToolContext(session=sessions.load())
|
|
45
|
+
try:
|
|
46
|
+
return await whoami(ctx)
|
|
47
|
+
except ToolError:
|
|
48
|
+
return None
|
|
49
|
+
finally:
|
|
50
|
+
await ctx.close()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _status(_: argparse.Namespace) -> None:
|
|
54
|
+
session = sessions.load()
|
|
55
|
+
if not session.signed_in:
|
|
56
|
+
sys.exit(f"No {app.NAME} session. Run: {app.CLI} connect")
|
|
57
|
+
who = asyncio.run(_whoami())
|
|
58
|
+
if not who:
|
|
59
|
+
sys.exit(f"{app.NAME} signed this session out. Sign in to {app.NAME} in Chrome, then run: {app.CLI} connect")
|
|
60
|
+
source = "your Chrome" if session.source == "auto" else f"Chrome at {urlsplit(session.source or '').netloc}"
|
|
61
|
+
print(f"Signed in to {app.NAME} as {who} (session from {source}, {sessions.session_path()})")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _tools(args: argparse.Namespace) -> None:
|
|
65
|
+
specs = tools(args.read_only)
|
|
66
|
+
if args.json:
|
|
67
|
+
rows = [{"name": s.name, "access": s.access, "route": s.route, "input_schema": s.input_schema} for s in specs]
|
|
68
|
+
print(json.dumps(rows, indent=2))
|
|
69
|
+
return
|
|
70
|
+
for spec in specs:
|
|
71
|
+
print(f"{spec.name:<30} {spec.access:<5} {spec.route:<62} {spec.description}")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _parse_args(tool: str, pairs: list[str]) -> dict[str, Any]:
|
|
75
|
+
"""key=value pairs; a value is JSON unless the tool's schema wants a string (IDs like 148213977)."""
|
|
76
|
+
if len(pairs) == 1 and pairs[0].lstrip().startswith("{"):
|
|
77
|
+
return json.loads(pairs[0])
|
|
78
|
+
spec = all_tools().get(tool)
|
|
79
|
+
properties = spec.input_schema.get("properties", {}) if spec else {}
|
|
80
|
+
out: dict[str, Any] = {}
|
|
81
|
+
for pair in pairs:
|
|
82
|
+
key, sep, value = pair.partition("=")
|
|
83
|
+
if not sep:
|
|
84
|
+
sys.exit(f"Arguments are key=value or one JSON object, got {pair!r}")
|
|
85
|
+
if properties.get(key, {}).get("type") == "string":
|
|
86
|
+
out[key] = value
|
|
87
|
+
continue
|
|
88
|
+
try:
|
|
89
|
+
out[key] = json.loads(value)
|
|
90
|
+
except ValueError:
|
|
91
|
+
out[key] = value
|
|
92
|
+
return out
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _call(args: argparse.Namespace) -> None:
|
|
96
|
+
runner = Runner(read_only=args.read_only)
|
|
97
|
+
|
|
98
|
+
async def go() -> Any:
|
|
99
|
+
try:
|
|
100
|
+
return await runner.run(args.tool, _parse_args(args.tool, args.arguments))
|
|
101
|
+
finally:
|
|
102
|
+
await runner.close()
|
|
103
|
+
|
|
104
|
+
try:
|
|
105
|
+
result = asyncio.run(go())
|
|
106
|
+
except ToolError as exc:
|
|
107
|
+
sys.exit(f"{exc.code}: {exc}")
|
|
108
|
+
print(json.dumps(result, indent=2, ensure_ascii=False))
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _mcp(args: argparse.Namespace) -> None:
|
|
112
|
+
from partiful_api_mcp.mcp_server import run_stdio
|
|
113
|
+
|
|
114
|
+
asyncio.run(run_stdio(Runner(read_only=args.read_only)))
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _serve(args: argparse.Namespace) -> None:
|
|
118
|
+
import uvicorn
|
|
119
|
+
|
|
120
|
+
from partiful_api_mcp.api import create_app
|
|
121
|
+
|
|
122
|
+
try:
|
|
123
|
+
loopback = ipaddress.ip_address(args.host).is_loopback
|
|
124
|
+
except ValueError:
|
|
125
|
+
loopback = args.host == "localhost"
|
|
126
|
+
if not loopback and not os.environ.get(f"{app.ENV}_MCP_TOKEN"):
|
|
127
|
+
sys.exit(
|
|
128
|
+
f"Listening beyond this machine needs {app.ENV}_MCP_TOKEN, or anyone on the network can use your {app.NAME} account."
|
|
129
|
+
)
|
|
130
|
+
print(
|
|
131
|
+
f"REST API http://{args.host}:{args.port}{app.API_PREFIX} docs http://{args.host}:{args.port}/docs",
|
|
132
|
+
file=sys.stderr,
|
|
133
|
+
)
|
|
134
|
+
print(f"MCP http://{args.host}:{args.port}/mcp", file=sys.stderr)
|
|
135
|
+
uvicorn.run(create_app(Runner(read_only=args.read_only)), host=args.host, port=args.port, log_level="warning")
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def main() -> None:
|
|
139
|
+
parser = argparse.ArgumentParser(
|
|
140
|
+
prog=app.CLI,
|
|
141
|
+
description=(__doc__ or "").replace("<cli>", app.CLI),
|
|
142
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
143
|
+
)
|
|
144
|
+
parser.add_argument("--version", action="version", version=__version__)
|
|
145
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
146
|
+
|
|
147
|
+
p = sub.add_parser("connect", help=f"read your {app.NAME} session from Chrome and save it")
|
|
148
|
+
p.add_argument(
|
|
149
|
+
"--cdp", help="DevTools address of a Chrome started with --remote-debugging-port, e.g. http://127.0.0.1:9222"
|
|
150
|
+
)
|
|
151
|
+
p.add_argument("--profile-dir", help="Chrome profile folder holding DevToolsActivePort, when not the default")
|
|
152
|
+
p.set_defaults(func=_connect)
|
|
153
|
+
|
|
154
|
+
p = sub.add_parser("status", help=f"check the saved session with {app.NAME}")
|
|
155
|
+
p.set_defaults(func=_status)
|
|
156
|
+
|
|
157
|
+
for name, func, text in (
|
|
158
|
+
("tools", _tools, "list the tools"),
|
|
159
|
+
("mcp", _mcp, "MCP server over stdio"),
|
|
160
|
+
("serve", _serve, "REST API and MCP over HTTP"),
|
|
161
|
+
):
|
|
162
|
+
p = sub.add_parser(name, help=text)
|
|
163
|
+
p.add_argument(
|
|
164
|
+
"--read-only",
|
|
165
|
+
action="store_true",
|
|
166
|
+
default=os.environ.get(f"{app.ENV}_MCP_READ_ONLY") == "1",
|
|
167
|
+
help="only tools that read",
|
|
168
|
+
)
|
|
169
|
+
p.set_defaults(func=func)
|
|
170
|
+
if name == "tools":
|
|
171
|
+
p.add_argument("--json", action="store_true", help="names, routes and input schemas as JSON")
|
|
172
|
+
if name == "serve":
|
|
173
|
+
p.add_argument("--host", default=os.environ.get(f"{app.ENV}_MCP_HOST", "127.0.0.1"))
|
|
174
|
+
p.add_argument("--port", type=int, default=int(os.environ.get(f"{app.ENV}_MCP_PORT", "8787")))
|
|
175
|
+
|
|
176
|
+
p = sub.add_parser("call", help="run one tool and print its JSON answer")
|
|
177
|
+
p.add_argument("tool")
|
|
178
|
+
p.add_argument("arguments", nargs="*", help="key=value pairs or one JSON object, e.g. status=going limit=10")
|
|
179
|
+
p.add_argument("--read-only", action="store_true")
|
|
180
|
+
p.set_defaults(func=_call)
|
|
181
|
+
|
|
182
|
+
args = parser.parse_args()
|
|
183
|
+
try:
|
|
184
|
+
args.func(args)
|
|
185
|
+
except ToolError as exc:
|
|
186
|
+
sys.exit(f"{exc.code}: {exc}")
|
|
187
|
+
except KeyboardInterrupt:
|
|
188
|
+
sys.exit(130)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
if __name__ == "__main__":
|
|
192
|
+
main()
|
|
File without changes
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Tools never change your account in the app: password, email, sign-in, two-factor, profile.
|
|
2
|
+
|
|
3
|
+
Checked on every request a tool makes, before it leaves. Reads stay allowed ("who am I" is a profile GET);
|
|
4
|
+
any other method to an account path is refused. The common paths are matched for every app, `app.ACCOUNT_PATHS`
|
|
5
|
+
adds the app's own.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from urllib.parse import urlsplit
|
|
12
|
+
|
|
13
|
+
from partiful_api_mcp import app
|
|
14
|
+
from partiful_api_mcp.core.errors import ErrorCode, ToolError
|
|
15
|
+
|
|
16
|
+
_READS = frozenset({"GET", "HEAD", "OPTIONS"})
|
|
17
|
+
_COMMON = re.compile(
|
|
18
|
+
r"passw|two[-_]?factor|2fa|(^|[/_-])(mfa|totp|otp)([/_-]|$)|recovery[-_]?code|"
|
|
19
|
+
r"(change|update|verify)[-_]?email|email[-_]?(change|update)|"
|
|
20
|
+
r"(delete|deactivate|close)[-_]?account|account[-_/](delete|deactivate|close)|"
|
|
21
|
+
r"(^|/)(log[-_]?out|sign[-_]?out|log[-_]?in|sign[-_]?in)([/?]|$)"
|
|
22
|
+
)
|
|
23
|
+
# Case-insensitive: the path is lowercased, the app's patterns keep its own spelling (getLoginToken).
|
|
24
|
+
_APP = [re.compile(pattern, re.IGNORECASE) for pattern in app.ACCOUNT_PATHS]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def check_account_write(method: str, url: str) -> None:
|
|
28
|
+
if method.upper() in _READS:
|
|
29
|
+
return
|
|
30
|
+
path = urlsplit(url).path.lower()
|
|
31
|
+
if _COMMON.search(path) or any(pattern.search(path) for pattern in _APP):
|
|
32
|
+
raise ToolError(
|
|
33
|
+
f"This server never changes your {app.NAME} account (password, email, sign-in, profile).",
|
|
34
|
+
ErrorCode.SCOPE_DENIED,
|
|
35
|
+
)
|