sesamcp 0.2.1__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.
sesamcp/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Sesamcp: an MCP server with real sign-in in front of any API."""
2
+
3
+ __version__ = "0.2.1"
sesamcp/access.py ADDED
@@ -0,0 +1,159 @@
1
+ """What a person can hand out and take back: the clients they connected, and API tokens for scripts.
2
+
3
+ access = Access(store, token_prefix="box_")
4
+ provider = LoginOAuthProvider(..., access=access) # check_login's grant names the person: {"person": ..., "label": ...}
5
+
6
+ A connection is one client a person signed in with. Every token stands on it, so revoking it stops that client at the next call; signing
7
+ in again makes a new one, and the old tokens stay dead. An API token acts as its person on the app's REST API (`rest_caller`) and never on
8
+ /mcp. Only its hash is stored.
9
+ """
10
+
11
+ import asyncio
12
+ import hashlib
13
+ import secrets
14
+ from collections.abc import Awaitable, Callable, Mapping
15
+ from dataclasses import dataclass
16
+ from datetime import UTC, datetime, timedelta
17
+ from typing import NamedTuple
18
+
19
+ from key_value.aio.protocols import AsyncKeyValue
20
+
21
+
22
+ class _Days(NamedTuple):
23
+ default: int
24
+ max: int
25
+
26
+
27
+ API_TOKEN_DAYS = _Days(default=90, max=365)
28
+ SCOPES = ("read", "read+write")
29
+ TOKEN_VIEW = ("id", "name", "scope", "start", "created_at", "expires_at", "last_used_at")
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class RestCaller:
34
+ person: str
35
+ actor: str
36
+ scope: str
37
+ kind: str = "token"
38
+
39
+
40
+ def _hash(text: str) -> str:
41
+ return hashlib.sha256(text.encode()).hexdigest()
42
+
43
+
44
+ def _iso(when: datetime) -> str:
45
+ return when.isoformat(timespec="milliseconds").replace("+00:00", "Z")
46
+
47
+
48
+ class Access:
49
+ def __init__(self, store: AsyncKeyValue, *, token_prefix: str, allowed: Callable[[str], Awaitable[bool]] | None = None):
50
+ """`allowed(person)` is asked at every call: a person it says no to is out, with every client and token they have."""
51
+ if not token_prefix:
52
+ raise ValueError("token_prefix must not be empty: it tells an API token from an access token")
53
+ self.store, self.token_prefix, self._allowed = store, token_prefix, allowed
54
+ # The store has no transactions: a person's record is read, changed and written by one task at a time.
55
+ self._lock = asyncio.Lock()
56
+
57
+ async def _record(self, person: str) -> dict:
58
+ return await self.store.get(_hash(person), collection="people") or {"connections": {}, "tokens": {}}
59
+
60
+ async def _save(self, person: str, record: dict) -> None:
61
+ await self.store.put(_hash(person), record, collection="people")
62
+
63
+ async def allows(self, person: str) -> bool:
64
+ return self._allowed is None or await self._allowed(person)
65
+
66
+ # -- connections ------------------------------------------------------------------------
67
+
68
+ async def connect(self, grant: dict, client_id: str, client_name: str) -> dict:
69
+ """The grant of a sign-in, standing on this person's connection to the client (made now, unless there is one)."""
70
+ person = grant.get("person")
71
+ if not isinstance(person, str) or not person:
72
+ raise ValueError("with access=, the grant of a sign-in needs the person: {'person': <id>, 'label': <name>}")
73
+ async with self._lock:
74
+ record = await self._record(person)
75
+ found = record["connections"].get(client_id)
76
+ if found is None:
77
+ found = {"id": secrets.token_urlsafe(12), "client_id": client_id, "client_name": client_name,
78
+ "created_at": _iso(datetime.now(UTC))}
79
+ record["connections"][client_id] = found
80
+ await self._save(person, record)
81
+ return {**grant, "connection": found["id"], "client_name": client_name}
82
+
83
+ async def stands(self, grant: dict) -> bool:
84
+ """Whether the person is still allowed in and the connection a grant stands on is still there."""
85
+ person = grant.get("person")
86
+ if not isinstance(person, str) or not await self.allows(person):
87
+ return False
88
+ return any(c["id"] == grant.get("connection") for c in (await self._record(person))["connections"].values())
89
+
90
+ async def connections(self, person: str) -> list[dict]:
91
+ """The person's connected clients, newest first."""
92
+ return sorted((await self._record(person))["connections"].values(), key=lambda c: c["created_at"], reverse=True)
93
+
94
+ async def revoke_connection(self, person: str, connection_id: str) -> bool:
95
+ async with self._lock:
96
+ record = await self._record(person)
97
+ kept = {client: c for client, c in record["connections"].items() if c["id"] != connection_id}
98
+ if len(kept) == len(record["connections"]):
99
+ return False
100
+ await self._save(person, {**record, "connections": kept})
101
+ return True
102
+
103
+ # -- API tokens -------------------------------------------------------------------------
104
+
105
+ async def create_api_token(self, person: str, label: str, *, name: str, scope: str,
106
+ expires_in_days: int | None = API_TOKEN_DAYS.default) -> dict:
107
+ """The new token (`token`, in this answer only) and what is known of it, or `{"error": why}`. None: it never expires."""
108
+ name = name.strip()
109
+ if not name or len(name) > 60:
110
+ return {"error": "a token needs a name of up to 60 characters"}
111
+ if scope not in SCOPES:
112
+ return {"error": 'the scope is "read" or "read+write"'}
113
+ if expires_in_days is not None and not 1 <= expires_in_days <= API_TOKEN_DAYS.max:
114
+ return {"error": f"a token lives 1 to {API_TOKEN_DAYS.max} days, or has no expiry when chosen explicitly"}
115
+ token = self.token_prefix + secrets.token_urlsafe(32)
116
+ now = datetime.now(UTC)
117
+ view = {"id": secrets.token_urlsafe(12), "name": name, "scope": scope, "start": token[:len(self.token_prefix) + 4],
118
+ "created_at": _iso(now), "last_used_at": None,
119
+ "expires_at": None if expires_in_days is None else _iso(now + timedelta(days=expires_in_days))}
120
+ async with self._lock:
121
+ record = await self._record(person)
122
+ record["tokens"][view["id"]] = {**view, "hash": _hash(token)}
123
+ await self.store.put(_hash(token), {"person": person, "label": label, "id": view["id"]}, collection="api_tokens")
124
+ await self._save(person, record)
125
+ return {**view, "token": token}
126
+
127
+ async def api_tokens(self, person: str) -> list[dict]:
128
+ """The person's API tokens, newest first; never the tokens themselves."""
129
+ tokens = sorted((await self._record(person))["tokens"].values(), key=lambda t: t["created_at"], reverse=True)
130
+ return [{k: t[k] for k in TOKEN_VIEW} for t in tokens]
131
+
132
+ async def revoke_api_token(self, person: str, token_id: str) -> bool:
133
+ async with self._lock:
134
+ record = await self._record(person)
135
+ found = record["tokens"].pop(token_id, None)
136
+ if found is None:
137
+ return False
138
+ await self.store.delete(found["hash"], collection="api_tokens")
139
+ await self._save(person, record)
140
+ return True
141
+
142
+ async def rest_caller(self, headers: Mapping[str, str]) -> RestCaller | None:
143
+ """Who a REST request is, by its `Authorization: Bearer <API token>`; None for anything else, an /mcp token included."""
144
+ scheme, _, token = headers.get("authorization", "").partition(" ")
145
+ token = token.strip()
146
+ if scheme.lower() != "bearer" or not token.startswith(self.token_prefix):
147
+ return None
148
+ pointer = await self.store.get(_hash(token), collection="api_tokens")
149
+ if pointer is None or not await self.allows(pointer["person"]):
150
+ return None
151
+ async with self._lock:
152
+ record = await self._record(pointer["person"])
153
+ found = record["tokens"].get(pointer["id"])
154
+ now = datetime.now(UTC)
155
+ if found is None or (found["expires_at"] and datetime.fromisoformat(found["expires_at"]) <= now):
156
+ return None
157
+ found["last_used_at"] = _iso(now)
158
+ await self._save(pointer["person"], record)
159
+ return RestCaller(person=pointer["person"], actor=pointer["label"], scope=found["scope"])
sesamcp/app.py ADDED
@@ -0,0 +1,169 @@
1
+ """The service: what the config file describes, served with its sign-in.
2
+
3
+ - proxy mode (`upstream`): the sign-in, the auth gate on /mcp, /health and /favicon.ico in front of an
4
+ existing MCP server; every request is forwarded with the person's credential added.
5
+ - openapi mode (`openapi`): tools generated from the app's spec (sesamcp.server), behind the same sign-in.
6
+
7
+ Everything about the app (the login page, how a login is checked, what is added to each request) comes
8
+ from the config file; see config.py and login.py.
9
+ """
10
+
11
+ import contextlib
12
+ import logging
13
+ import re
14
+ import sys
15
+ from pathlib import Path
16
+ from urllib.parse import urlsplit
17
+
18
+ import httpx
19
+ import httpx2
20
+ import yaml
21
+ from fastmcp.server.auth.middleware import RequireAuthMiddleware
22
+ from mcp.server.auth.routes import build_resource_metadata_url
23
+ from mcp.types import Icon
24
+ from pydantic import AnyHttpUrl
25
+ from starlette.applications import Starlette
26
+ from starlette.requests import Request
27
+ from starlette.responses import JSONResponse, RedirectResponse, Response
28
+ from starlette.routing import Route
29
+
30
+ from sesamcp.config import SpecHeader, Config, ConfigError
31
+ from sesamcp.credentials import headers_for, pick
32
+ from sesamcp.login import build_provider
33
+ from sesamcp.proxy.forward import Forwarder
34
+ from sesamcp.server import allowed_hosts, build_error_server, build_http_app, build_server
35
+ from sesamcp.signin import BearerPrefixMiddleware, OriginMiddleware
36
+ from sesamcp.tools.overlay import OverlayError, apply_overlay
37
+ from sesamcp.tools.select import is_operation, resolve_toolsets, without_headers
38
+ from sesamcp.tools.spec import SpecSource, resolve_spec
39
+
40
+ MCP_PATH = "/mcp"
41
+
42
+ __all__ = ["MCP_PATH", "build_openapi_app", "build_provider", "build_proxy_app", "build_service_app"]
43
+
44
+ log = logging.getLogger("sesamcp")
45
+
46
+
47
+ def build_proxy_app(config: Config, store_dir: Path = Path("/data/oauth"),
48
+ transport: httpx.AsyncBaseTransport | None = None, **provider_overrides):
49
+ """`transport` and `provider_overrides` are for tests (a fake upstream, failed_login_delay=0)."""
50
+ service = config.service
51
+ parts = urlsplit(service.upstream)
52
+ # No total timeout: event streams and long tool calls stay open as long as the upstream keeps them.
53
+ client = httpx.AsyncClient(base_url=f"{parts.scheme}://{parts.netloc}", transport=transport,
54
+ timeout=httpx.Timeout(connect=10, read=None, write=60, pool=10))
55
+ provider = build_provider(config, client, store_dir, **provider_overrides)
56
+ metadata_url = build_resource_metadata_url(AnyHttpUrl(config.base_url + MCP_PATH))
57
+ forwarder = Forwarder(client, parts.path or "/", lambda grant: headers_for(service, grant),
58
+ service.instructions)
59
+ gate = RequireAuthMiddleware(forwarder, provider.required_scopes or [], metadata_url)
60
+
61
+ async def health(_: Request) -> JSONResponse:
62
+ if not service.health:
63
+ return JSONResponse({"status": "ok"})
64
+ try:
65
+ ok = (await client.get(service.health, timeout=5)).is_success
66
+ except httpx.HTTPError:
67
+ ok = False
68
+ return JSONResponse({"status": "ok", "upstream": "ok" if ok else "unreachable"})
69
+
70
+ async def favicon(_: Request) -> Response:
71
+ # Clients that take a connector's icon from its domain's favicon get the upstream app's.
72
+ if not service.favicon:
73
+ return Response(status_code=404)
74
+ return RedirectResponse(str(service.favicon), status_code=302)
75
+
76
+ @contextlib.asynccontextmanager
77
+ async def lifespan(_):
78
+ yield
79
+ await client.aclose()
80
+
81
+ app = Starlette(routes=[*provider.get_routes(mcp_path=MCP_PATH), Route("/health", health),
82
+ Route("/favicon.ico", favicon), Route(MCP_PATH, gate, methods=["GET", "POST", "DELETE"])],
83
+ middleware=provider.get_middleware(), lifespan=lifespan)
84
+ return OriginMiddleware(BearerPrefixMiddleware(app), config.base_url, MCP_PATH)
85
+
86
+
87
+ def patched(spec: dict, overlay: Path) -> dict:
88
+ try:
89
+ return apply_overlay(spec, yaml.safe_load(overlay.read_text()))
90
+ except (OSError, yaml.YAMLError, OverlayError) as e:
91
+ raise ConfigError(f"overlay {overlay.name}: {e}") from None
92
+
93
+
94
+ def spec_values(header: str | SpecHeader, spec: dict) -> str:
95
+ """`{spec.info.version}` filled from the loaded spec, or the part of it `match` captures."""
96
+ text, pattern = (header, None) if isinstance(header, str) else (header.value, header.match)
97
+
98
+ def value(m: re.Match) -> str:
99
+ try:
100
+ found = str(pick(spec, m.group(1)))
101
+ except KeyError:
102
+ raise ConfigError(f"openapi.headers: the spec holds no {{spec.{m.group(1)}}}") from None
103
+ part = re.search(pattern, found) if pattern else None
104
+ if pattern and not part:
105
+ raise ConfigError(f"openapi.headers: {m.group(1)} is {found!r}, which {pattern} does not match")
106
+ return part.group(1) if part else found
107
+ return re.sub(r"\{spec\.([\w.-]+)\}", value, text)
108
+
109
+
110
+ def check_names(spec: dict, sets: dict[str, list[str]], *, ours: bool) -> None:
111
+ """A misspelt operation in an annotation set would silently change nothing: refuse it where the config
112
+ brings the spec. A spec the app brings changes with its releases, and one renamed operation must not
113
+ take every tool away: that is logged."""
114
+ known = {op["operationId"] for item in spec["paths"].values() for op in item.values() if is_operation(op)}
115
+ for where, names in sets.items():
116
+ if unknown := sorted(set(names) - known):
117
+ problem = f"openapi.{where} names {', '.join(unknown)}, which the spec does not have"
118
+ if ours:
119
+ raise ConfigError(problem)
120
+ log.warning(problem)
121
+
122
+
123
+ def build_openapi_app(config: Config, store_dir: Path = Path("/data/oauth"), *, env: dict | None = None,
124
+ api_transport: httpx2.AsyncBaseTransport | None = None,
125
+ spec_transport: httpx2.BaseTransport | None = None,
126
+ http_app_args: dict | None = None, **provider_overrides):
127
+ """Tools generated from the app's spec, behind the config's sign-in. A spec that can't be loaded
128
+ gives the error server instead, which says why over a live connection."""
129
+ service, openapi = config.service, config.service.openapi
130
+ name = openapi.name or f"{service.service_name} MCP"
131
+ http_app_args = http_app_args or {}
132
+ source = SpecSource(**openapi.spec.model_dump())
133
+ try:
134
+ spec, origin = resolve_spec(source, transport=spec_transport)
135
+ for overlay in openapi.overlays:
136
+ spec = patched(spec, overlay)
137
+ static_headers = {k: spec_values(v, spec) for k, v in openapi.headers.items()}
138
+ check_names(spec, openapi.annotation_sets, ours=bool(openapi.spec.file))
139
+ spec = without_headers(spec, {*service.upstream_headers, *static_headers, "Authorization"})
140
+ except Exception as e: # noqa: BLE001 — every cause is shown by the error server
141
+ print(f"sesamcp: {e}", file=sys.stderr)
142
+ return build_http_app(build_error_server(name, e), "token", **http_app_args)
143
+ print(f"OpenAPI spec: {origin}", file=sys.stderr)
144
+ login_client = httpx.AsyncClient(timeout=30)
145
+ provider = build_provider(config, login_client, store_dir, **provider_overrides)
146
+ toolsets = resolve_toolsets(openapi.toolsets or (), (env or {}).get("MCP_TOOLSETS", ""))
147
+
148
+ def headers(grant: dict) -> dict[str, str]:
149
+ return {k.decode("latin-1"): v.decode("latin-1") for k, v in headers_for(service, grant)}
150
+
151
+ mcp = build_server(name=name, service_name=service.service_name, spec=spec, headers_for=headers,
152
+ toolsets=toolsets, auth=provider, static_variable=service.static_tokens,
153
+ never_exposed=tuple(openapi.never_exposed), toolset_prefix=openapi.toolset_prefix,
154
+ max_file_bytes=openapi.max_file_bytes, max_upload_bytes=openapi.max_upload_bytes,
155
+ fetch_hosts=openapi.fetch_hosts, fetch_private=openapi.fetch_private,
156
+ guides=openapi.guides, annotation_sets=openapi.annotation_sets,
157
+ instructions=service.instructions, permission_hint=service.permission_hint,
158
+ icons=[Icon(src=str(i.src), mime_type=i.mime_type, sizes=i.sizes) for i in service.icons] or None,
159
+ favicon=str(service.favicon) if service.favicon else None,
160
+ client=httpx2.AsyncClient(base_url=openapi.api_url, transport=api_transport, timeout=60,
161
+ headers=static_headers))
162
+ return build_http_app(mcp, "both", path=MCP_PATH, allowed_hosts=allowed_hosts(env or {}) or None, **http_app_args)
163
+
164
+
165
+ def build_service_app(config: Config, store_dir: Path = Path("/data/oauth"), *, env: dict | None = None, **kwargs):
166
+ """Proxy or openapi mode, as the config says: the app `sesamcp` serves."""
167
+ if config.service.openapi:
168
+ return build_openapi_app(config, store_dir, env=env, **kwargs)
169
+ return build_proxy_app(config, store_dir, **kwargs)
sesamcp/cli.py ADDED
@@ -0,0 +1,59 @@
1
+ """The `sesamcp` command: serve the config file's service, `sesamcp hash`, `sesamcp check <file>`."""
2
+
3
+ import getpass
4
+ import logging
5
+ import os
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from sesamcp.config import FORM_KINDS, ConfigError, load_config, load_service_config
10
+ from sesamcp.login import hash_password
11
+
12
+
13
+ def hash_command() -> int:
14
+ """`sesamcp hash`: read a password twice without echo and print its argon2id hash."""
15
+ password = getpass.getpass("Password: ")
16
+ if not password:
17
+ print("sesamcp: the password is empty", file=sys.stderr)
18
+ return 1
19
+ if getpass.getpass("Again: ") != password:
20
+ print("sesamcp: the passwords differ", file=sys.stderr)
21
+ return 1
22
+ print(hash_password(password))
23
+ return 0
24
+
25
+
26
+ def check_command(path: str) -> int:
27
+ """`sesamcp check <file>`: load a config the way the service does (with this environment)."""
28
+ try:
29
+ service = load_service_config(Path(path), os.environ)
30
+ except ConfigError as e:
31
+ print(f"sesamcp: {e}", file=sys.stderr)
32
+ return 1
33
+ mode = "openapi" if service.openapi else "proxy"
34
+ ways = [k for k in (*FORM_KINDS, "oidc") if getattr(service.login, k) is not None]
35
+ print(f"{path}: ok ({mode} mode, {service.service_name}, sign-in: {' + '.join(ways)})")
36
+ return 0
37
+
38
+
39
+ def main() -> None:
40
+ if sys.argv[1:] == ["hash"]:
41
+ sys.exit(hash_command())
42
+ if sys.argv[1:2] == ["check"]:
43
+ if len(sys.argv) != 3:
44
+ print("usage: sesamcp check <config.yaml>", file=sys.stderr)
45
+ sys.exit(2)
46
+ sys.exit(check_command(sys.argv[2]))
47
+ logging.basicConfig(level=os.environ.get("LOG_LEVEL", "INFO"),
48
+ format="%(asctime)s %(levelname)s %(name)s: %(message)s")
49
+ try:
50
+ config = load_config(os.environ)
51
+ except ConfigError as e:
52
+ print(f"sesamcp: {e}", file=sys.stderr)
53
+ sys.exit(1)
54
+ import uvicorn
55
+
56
+ from sesamcp.app import build_service_app
57
+ app = build_service_app(config, Path(os.environ.get("SESAMCP_DATA", "").strip() or "/data/oauth"), env=dict(os.environ))
58
+ uvicorn.run(app, host=os.environ.get("MCP_HOST", "0.0.0.0"), port=config.port, log_level="warning",
59
+ proxy_headers=False) # the sign-in reads X-Forwarded-For itself (signin/limit.py)