second-brain-core 0.1.0__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.
- second_brain_core/__init__.py +32 -0
- second_brain_core/annotations.py +15 -0
- second_brain_core/audit.py +275 -0
- second_brain_core/auth.py +235 -0
- second_brain_core/env.py +171 -0
- second_brain_core/errors.py +37 -0
- second_brain_core/failure.py +87 -0
- second_brain_core/health.py +48 -0
- second_brain_core/py.typed +0 -0
- second_brain_core/recent.py +69 -0
- second_brain_core/remote.py +252 -0
- second_brain_core/semantic/__init__.py +7 -0
- second_brain_core/semantic/chunking.py +48 -0
- second_brain_core/semantic/embedders.py +68 -0
- second_brain_core/semantic/engine.py +218 -0
- second_brain_core/semantic/stores.py +539 -0
- second_brain_core/semantic/sync.py +17 -0
- second_brain_core/semantic/testing.py +183 -0
- second_brain_core/semantic/types.py +130 -0
- second_brain_core/server.py +44 -0
- second_brain_core/testing.py +57 -0
- second_brain_core-0.1.0.dist-info/METADATA +106 -0
- second_brain_core-0.1.0.dist-info/RECORD +25 -0
- second_brain_core-0.1.0.dist-info/WHEEL +4 -0
- second_brain_core-0.1.0.dist-info/licenses/LICENSE +661 -0
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""second-brain-core: what the Second Brain MCP servers share.
|
|
2
|
+
|
|
3
|
+
Sign-in, the audit log, HTTP serving, the start-up guardrails, and (with the
|
|
4
|
+
``semantic`` extra) search by meaning. Each server describes itself once with a
|
|
5
|
+
:class:`~second_brain_core.server.Server` and hands that to every shared piece,
|
|
6
|
+
so nothing in here names a product.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
|
|
11
|
+
__version__ = "0.1.0"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def pin_fastmcp_env() -> None:
|
|
15
|
+
"""Stop FastMCP from reading its settings from the working directory's ``.env``.
|
|
16
|
+
|
|
17
|
+
FastMCP, the library underneath, has settings of its own (``FASTMCP_*``), and
|
|
18
|
+
when it is first imported it reads them from a ``.env`` in the working
|
|
19
|
+
directory. For an MCP server the working directory is whatever project the
|
|
20
|
+
client has open, and those settings include the transport: a project's
|
|
21
|
+
``.env`` must not be able to turn a local stdio server into an HTTP one.
|
|
22
|
+
Naming an env file that isn't a file stops the read. It leaves alone a
|
|
23
|
+
``FASTMCP_ENV_FILE`` the operator set on purpose.
|
|
24
|
+
|
|
25
|
+
It must run before anything imports fastmcp. Importing this package runs it,
|
|
26
|
+
so a server's ``__init__`` only has to import ``second_brain_core`` first;
|
|
27
|
+
calling it again is harmless.
|
|
28
|
+
"""
|
|
29
|
+
os.environ.setdefault("FASTMCP_ENV_FILE", os.devnull)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
pin_fastmcp_env()
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""MCP tool annotations every server uses the same way.
|
|
2
|
+
|
|
3
|
+
Clients use these hints, e.g. to skip a confirmation prompt for a read-only tool.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from mcp.types import ToolAnnotations
|
|
7
|
+
|
|
8
|
+
# Reads the store, changes nothing, and touches nothing beyond this machine.
|
|
9
|
+
READ_ONLY = ToolAnnotations(read_only_hint=True, open_world_hint=False)
|
|
10
|
+
|
|
11
|
+
# Asks the client to have a person approve every call of a tool, as tool metadata.
|
|
12
|
+
# Claude's clients read it; others ignore it. A server lets the operator turn it
|
|
13
|
+
# off, and then the check on each call is whatever the client does for any tool
|
|
14
|
+
# that writes.
|
|
15
|
+
ASK_EVERY_TIME = {"anthropic/requiresUserInteraction": True}
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
"""What HTTP mode logs, and what it never logs.
|
|
2
|
+
|
|
3
|
+
A long-running server needs a record of who called what, and that record must
|
|
4
|
+
never hold the content it serves or credentials. Each tool call logs one line:
|
|
5
|
+
the tool, the caller's GitHub id, the client it came from, the outcome and the
|
|
6
|
+
duration. Never arguments (a search query is content), never results, never tokens.
|
|
7
|
+
|
|
8
|
+
**The client's name** (``client=``) is what the client says about itself, so it is
|
|
9
|
+
a hint for the operator reading the log, never proof, and nothing is decided by it.
|
|
10
|
+
It is taken from the first of: the name the client registered under at sign-in, the
|
|
11
|
+
name it gives in the MCP handshake (or in each request, on protocols without one),
|
|
12
|
+
the first word of its ``User-Agent``. It keeps letters, digits and ``._/-`` only
|
|
13
|
+
(anything else becomes ``_``), at most 40 characters, so it can't break or forge a
|
|
14
|
+
line; with none of these it is ``unknown``.
|
|
15
|
+
|
|
16
|
+
Four leaks are closed by configuration rather than code:
|
|
17
|
+
|
|
18
|
+
- **HTTP client request logging.** A store's API token can ride in a URL's query
|
|
19
|
+
string (Joplin's API takes it no other way), so httpx's INFO line for each
|
|
20
|
+
request would print it. The HTTP client loggers are pinned to WARNING.
|
|
21
|
+
- **uvicorn's access log.** The OAuth callback URL carries the authorization code
|
|
22
|
+
in its query string. The access log is off (see ``remote.run_http``).
|
|
23
|
+
- **FastMCP's debug log.** At DEBUG it prints every tool call with its arguments.
|
|
24
|
+
Its loggers, and any a server names, are held at INFO or above.
|
|
25
|
+
- **FastMCP's error log.** When an exception escapes a tool, FastMCP logs "Error
|
|
26
|
+
calling tool" with the traceback, and the exception's text with it, which can
|
|
27
|
+
quote what was being processed. The traceback is dropped from that line; the
|
|
28
|
+
tool's name stays, and the audit line names the class.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
import logging
|
|
32
|
+
import re
|
|
33
|
+
import sys
|
|
34
|
+
import time
|
|
35
|
+
from collections import OrderedDict
|
|
36
|
+
from collections.abc import Sequence
|
|
37
|
+
from contextvars import ContextVar
|
|
38
|
+
from typing import Any, Protocol, runtime_checkable
|
|
39
|
+
|
|
40
|
+
from fastmcp.exceptions import ToolError
|
|
41
|
+
from fastmcp.server.dependencies import get_access_token, get_http_headers
|
|
42
|
+
from fastmcp.server.middleware import CallNext, Middleware, MiddlewareContext
|
|
43
|
+
from fastmcp.server.middleware.rate_limiting import RateLimitingMiddleware
|
|
44
|
+
|
|
45
|
+
from .server import Server
|
|
46
|
+
|
|
47
|
+
# Loggers that would print request URLs, and with them a token.
|
|
48
|
+
QUIET_LOGGERS = ("httpx", "httpcore", "httpx2", "httpcore2")
|
|
49
|
+
# Loggers that print each tool call's arguments at DEBUG. Arguments are content,
|
|
50
|
+
# so these stay at INFO or above.
|
|
51
|
+
NO_DEBUG_LOGGERS = ("fastmcp", "mcp")
|
|
52
|
+
LOG_FORMAT = "%(asctime)s %(levelname)s %(name)s: %(message)s"
|
|
53
|
+
ANONYMOUS = "anonymous"
|
|
54
|
+
UNKNOWN = "unknown"
|
|
55
|
+
CLIENT_NAME_LENGTH = 40
|
|
56
|
+
_NOT_IN_A_NAME = re.compile(r"[^A-Za-z0-9._/-]+")
|
|
57
|
+
# The client of the tool call being handled, for the lines a tool logs itself.
|
|
58
|
+
_THIS_CALLS_CLIENT: ContextVar[str] = ContextVar("second_brain_core_client", default=UNKNOWN)
|
|
59
|
+
# Marks the handler configure_logging adds, so a second call adds none.
|
|
60
|
+
_HANDLER_MARK = "_second_brain_core"
|
|
61
|
+
# Where FastMCP logs a failed tool call (fastmcp/server/server.py).
|
|
62
|
+
FASTMCP_SERVER_LOGGER = "fastmcp.server.server"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class NoTraceback(logging.Filter):
|
|
66
|
+
"""Drops the traceback (and with it the exception's text) from a log record."""
|
|
67
|
+
|
|
68
|
+
def filter(self, record: logging.LogRecord) -> bool:
|
|
69
|
+
record.exc_info = None
|
|
70
|
+
record.exc_text = None
|
|
71
|
+
record.stack_info = None
|
|
72
|
+
return True
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def outcome_name(exc: BaseException, named: tuple[type[BaseException], ...] = ()) -> str:
|
|
76
|
+
"""The class name the log gives a failed call: the cause, if it is a named one.
|
|
77
|
+
|
|
78
|
+
A tool turns a server's own failures into a ``ToolError``; the log names the
|
|
79
|
+
cause instead, so an operator can count outages from it. A class name only,
|
|
80
|
+
never the message: messages can quote what the caller sent.
|
|
81
|
+
"""
|
|
82
|
+
cause = exc.__cause__
|
|
83
|
+
if named and isinstance(exc, ToolError) and isinstance(cause, named):
|
|
84
|
+
return type(cause).__name__
|
|
85
|
+
return type(exc).__name__
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def caller_id(_context: MiddlewareContext[Any] | None = None) -> str:
|
|
89
|
+
"""The caller's GitHub user id, or ``anonymous`` with no sign-in."""
|
|
90
|
+
token = get_access_token()
|
|
91
|
+
if token is None:
|
|
92
|
+
return ANONYMOUS
|
|
93
|
+
user_id = token.claims.get("sub")
|
|
94
|
+
return user_id if isinstance(user_id, str) and user_id else ANONYMOUS
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def clean_client_name(raw: object) -> str | None:
|
|
98
|
+
"""``raw`` as a short, safe word for the log, or None when nothing is left of it."""
|
|
99
|
+
if not isinstance(raw, str):
|
|
100
|
+
return None
|
|
101
|
+
cleaned = _NOT_IN_A_NAME.sub("_", raw.strip()).strip("_")[:CLIENT_NAME_LENGTH]
|
|
102
|
+
return cleaned.strip("_") or None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@runtime_checkable
|
|
106
|
+
class RegisteredClients(Protocol):
|
|
107
|
+
"""What knows the clients registered at sign-in (FastMCP's OAuth proxy does)."""
|
|
108
|
+
|
|
109
|
+
async def get_client(self, client_id: str) -> Any: ...
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class ClientNames:
|
|
113
|
+
"""The names clients registered under at sign-in, remembered by client id.
|
|
114
|
+
|
|
115
|
+
A registration doesn't change its name, so each id is looked up once; at most
|
|
116
|
+
``at_most`` ids are kept.
|
|
117
|
+
"""
|
|
118
|
+
|
|
119
|
+
def __init__(self, registry: RegisteredClients, at_most: int = 64) -> None:
|
|
120
|
+
self._registry = registry
|
|
121
|
+
self._at_most = at_most
|
|
122
|
+
self._known: OrderedDict[str, str | None] = OrderedDict()
|
|
123
|
+
|
|
124
|
+
async def name_of(self, client_id: str) -> str | None:
|
|
125
|
+
if client_id in self._known:
|
|
126
|
+
return self._known[client_id]
|
|
127
|
+
try:
|
|
128
|
+
client = await self._registry.get_client(client_id)
|
|
129
|
+
except Exception:
|
|
130
|
+
return None # not remembered: the next call asks again
|
|
131
|
+
name = clean_client_name(getattr(client, "client_name", None))
|
|
132
|
+
self._known[client_id] = name
|
|
133
|
+
while len(self._known) > self._at_most:
|
|
134
|
+
self._known.popitem(last=False)
|
|
135
|
+
return name
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
async def client_name(context: MiddlewareContext[Any], names: ClientNames | None = None) -> str:
|
|
139
|
+
"""The calling client's name for the log; see the module's docstring."""
|
|
140
|
+
token = get_access_token()
|
|
141
|
+
if names is not None and token is not None and token.client_id:
|
|
142
|
+
registered = await names.name_of(token.client_id)
|
|
143
|
+
if registered:
|
|
144
|
+
return registered
|
|
145
|
+
fastmcp_context = context.fastmcp_context
|
|
146
|
+
try:
|
|
147
|
+
params = fastmcp_context.session.client_params if fastmcp_context else None
|
|
148
|
+
except RuntimeError: # no session (yet)
|
|
149
|
+
params = None
|
|
150
|
+
info = getattr(params, "client_info", None)
|
|
151
|
+
told = clean_client_name(getattr(info, "name", None))
|
|
152
|
+
if told:
|
|
153
|
+
return told
|
|
154
|
+
agent = get_http_headers().get("user-agent", "").split()
|
|
155
|
+
from_agent = clean_client_name(agent[0]) if agent else None
|
|
156
|
+
return from_agent or UNKNOWN
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def this_calls_client() -> str:
|
|
160
|
+
"""The client of the tool call being handled, for a line a tool logs itself."""
|
|
161
|
+
return _THIS_CALLS_CLIENT.get()
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
class AuditMiddleware(Middleware):
|
|
165
|
+
"""Log one line per tool call: tool, caller, client, outcome, duration. Nothing else.
|
|
166
|
+
|
|
167
|
+
``named_causes`` are the server's own failure classes, logged by name (see
|
|
168
|
+
:func:`outcome_name`). ``client_names`` looks up the name a client registered
|
|
169
|
+
under at sign-in (HTTP mode with sign-in).
|
|
170
|
+
"""
|
|
171
|
+
|
|
172
|
+
def __init__(
|
|
173
|
+
self,
|
|
174
|
+
server: Server,
|
|
175
|
+
named_causes: Sequence[type[BaseException]] = (),
|
|
176
|
+
client_names: ClientNames | None = None,
|
|
177
|
+
) -> None:
|
|
178
|
+
self._log = server.logger("audit")
|
|
179
|
+
self._named = tuple(named_causes)
|
|
180
|
+
self._names = client_names
|
|
181
|
+
|
|
182
|
+
async def on_call_tool(
|
|
183
|
+
self, context: MiddlewareContext[Any], call_next: CallNext[Any, Any]
|
|
184
|
+
) -> Any:
|
|
185
|
+
# The tool's name is what the client asked for, so it is cleaned like the
|
|
186
|
+
# client's: an unknown name with a line break must not forge a line.
|
|
187
|
+
tool = clean_client_name(getattr(context.message, "name", None)) or "?"
|
|
188
|
+
who = caller_id(context)
|
|
189
|
+
client = await client_name(context, self._names)
|
|
190
|
+
token = _THIS_CALLS_CLIENT.set(client)
|
|
191
|
+
started = time.perf_counter()
|
|
192
|
+
try:
|
|
193
|
+
result = await call_next(context)
|
|
194
|
+
except Exception as exc:
|
|
195
|
+
self._log.info(
|
|
196
|
+
"tool=%s caller=%s client=%s outcome=error:%s ms=%d",
|
|
197
|
+
tool,
|
|
198
|
+
who,
|
|
199
|
+
client,
|
|
200
|
+
outcome_name(exc, self._named),
|
|
201
|
+
(time.perf_counter() - started) * 1000,
|
|
202
|
+
)
|
|
203
|
+
raise
|
|
204
|
+
finally:
|
|
205
|
+
_THIS_CALLS_CLIENT.reset(token)
|
|
206
|
+
outcome = "error" if getattr(result, "is_error", False) else "ok"
|
|
207
|
+
self._log.info(
|
|
208
|
+
"tool=%s caller=%s client=%s outcome=%s ms=%d",
|
|
209
|
+
tool,
|
|
210
|
+
who,
|
|
211
|
+
client,
|
|
212
|
+
outcome,
|
|
213
|
+
(time.perf_counter() - started) * 1000,
|
|
214
|
+
)
|
|
215
|
+
return result
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
class ToolCallRateLimit(RateLimitingMiddleware):
|
|
219
|
+
"""FastMCP's token-bucket limiter, counting tool calls only.
|
|
220
|
+
|
|
221
|
+
The stock middleware counts every MCP request, and one tool call from a client
|
|
222
|
+
brings protocol requests with it (discovery, ``tools/list``), so a "60 a minute"
|
|
223
|
+
limit would really mean a third of that. Listing and discovery are cheap; tool
|
|
224
|
+
calls are what reach the store and the embedding model.
|
|
225
|
+
"""
|
|
226
|
+
|
|
227
|
+
async def on_request(
|
|
228
|
+
self, context: MiddlewareContext[Any], call_next: CallNext[Any, Any]
|
|
229
|
+
) -> Any:
|
|
230
|
+
return await call_next(context)
|
|
231
|
+
|
|
232
|
+
async def on_call_tool(
|
|
233
|
+
self, context: MiddlewareContext[Any], call_next: CallNext[Any, Any]
|
|
234
|
+
) -> Any:
|
|
235
|
+
return await super().on_request(context, call_next)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def rate_limit(per_minute: int) -> ToolCallRateLimit:
|
|
239
|
+
"""A per-caller token bucket of tool calls: ``per_minute`` sustained, bursts of half.
|
|
240
|
+
|
|
241
|
+
Keyed by GitHub id (FastMCP's default is one bucket shared by every caller).
|
|
242
|
+
"""
|
|
243
|
+
if per_minute < 1:
|
|
244
|
+
raise ValueError("per_minute must be at least 1")
|
|
245
|
+
return ToolCallRateLimit(
|
|
246
|
+
max_requests_per_second=per_minute / 60,
|
|
247
|
+
burst_capacity=max(1, per_minute // 2),
|
|
248
|
+
get_client_id=caller_id,
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def configure_logging(
|
|
253
|
+
server: Server, *, no_debug: Sequence[str] = (), level: int = logging.INFO
|
|
254
|
+
) -> None:
|
|
255
|
+
"""Logging for HTTP mode: the server's lines on stderr, URL loggers quiet.
|
|
256
|
+
|
|
257
|
+
``no_debug`` names more loggers that would print content at DEBUG (a protocol
|
|
258
|
+
library's, say). Idempotent: calling it twice adds no second handler.
|
|
259
|
+
"""
|
|
260
|
+
package = logging.getLogger(server.package)
|
|
261
|
+
package.setLevel(level)
|
|
262
|
+
if not any(getattr(h, _HANDLER_MARK, False) for h in package.handlers):
|
|
263
|
+
handler = logging.StreamHandler(sys.stderr)
|
|
264
|
+
handler.setFormatter(logging.Formatter(LOG_FORMAT))
|
|
265
|
+
setattr(handler, _HANDLER_MARK, True)
|
|
266
|
+
package.addHandler(handler)
|
|
267
|
+
for name in QUIET_LOGGERS:
|
|
268
|
+
logging.getLogger(name).setLevel(logging.WARNING)
|
|
269
|
+
for name in (*NO_DEBUG_LOGGERS, *no_debug):
|
|
270
|
+
chatty = logging.getLogger(name)
|
|
271
|
+
if chatty.getEffectiveLevel() < logging.INFO:
|
|
272
|
+
chatty.setLevel(logging.INFO)
|
|
273
|
+
fastmcp_server = logging.getLogger(FASTMCP_SERVER_LOGGER)
|
|
274
|
+
if not any(isinstance(f, NoTraceback) for f in fastmcp_server.filters):
|
|
275
|
+
fastmcp_server.addFilter(NoTraceback())
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"""GitHub sign-in for HTTP mode, limited to listed GitHub accounts.
|
|
2
|
+
|
|
3
|
+
Claude's custom connectors sign in with OAuth, registering themselves through
|
|
4
|
+
Dynamic Client Registration or a Client ID Metadata Document. GitHub does neither,
|
|
5
|
+
so FastMCP's :class:`OAuthProxy` stands in front of it: it presents DCR and CIMD to
|
|
6
|
+
Claude, sends the person to GitHub to sign in, and hands Claude a token of its own.
|
|
7
|
+
|
|
8
|
+
GitHub sign-in alone would admit **any** GitHub account, so every request's token
|
|
9
|
+
is checked against ``<prefix>ALLOWED_GITHUB_IDS``, a list of numeric GitHub user ids.
|
|
10
|
+
Ids, not logins: a login can be renamed and then registered by somebody else, an
|
|
11
|
+
id never changes. Anyone else gets 401 before any MCP message is read.
|
|
12
|
+
|
|
13
|
+
This builds the proxy the way FastMCP's ``GitHubProvider`` does, with one change:
|
|
14
|
+
the token verifier is our allowlisting subclass, which ``GitHubProvider`` gives no
|
|
15
|
+
way to pass in.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import os
|
|
19
|
+
import re
|
|
20
|
+
from collections.abc import Mapping
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
|
|
23
|
+
import httpx2
|
|
24
|
+
from fastmcp.server.auth import AccessToken
|
|
25
|
+
from fastmcp.server.auth.oauth_proxy import OAuthProxy
|
|
26
|
+
from fastmcp.server.auth.providers.github import GitHubTokenVerifier
|
|
27
|
+
from fastmcp.utilities.authorization import AuthContext
|
|
28
|
+
from key_value.aio.protocols import AsyncKeyValue
|
|
29
|
+
|
|
30
|
+
from .errors import ServeConfigError
|
|
31
|
+
from .server import Server
|
|
32
|
+
|
|
33
|
+
GITHUB_AUTHORIZE_URL = "https://github.com/login/oauth/authorize"
|
|
34
|
+
GITHUB_TOKEN_URL = "https://github.com/login/oauth/access_token"
|
|
35
|
+
CALLBACK_PATH = "/auth/callback"
|
|
36
|
+
# Read the profile only. FastMCP's default, ``user``, also allows writing it.
|
|
37
|
+
GITHUB_SCOPES = ["read:user"]
|
|
38
|
+
# Each verified token is remembered this long, instead of two GitHub API calls per
|
|
39
|
+
# MCP request (FastMCP's default is no cache).
|
|
40
|
+
VERIFY_CACHE_SECONDS = 300
|
|
41
|
+
# claude.ai's OAuth callback, the only client allowed to register by default
|
|
42
|
+
# (https://claude.com/docs/connectors/building/authentication).
|
|
43
|
+
CLAUDE_CALLBACK = "https://claude.ai/api/mcp/auth_callback"
|
|
44
|
+
MIN_SIGNING_KEY_LENGTH = 32
|
|
45
|
+
|
|
46
|
+
# Without the prefix: ``Server.var`` adds it.
|
|
47
|
+
REQUIRED = ("GITHUB_CLIENT_ID", "GITHUB_CLIENT_SECRET", "JWT_SIGNING_KEY", "ALLOWED_GITHUB_IDS")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def required_variables(server: Server) -> tuple[str, ...]:
|
|
51
|
+
"""The variables sign-in needs, all or none."""
|
|
52
|
+
return tuple(server.var(name) for name in REQUIRED)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True, repr=False)
|
|
56
|
+
class AuthSettings:
|
|
57
|
+
"""Sign-in configuration. ``repr`` is off so a secret never lands in a log."""
|
|
58
|
+
|
|
59
|
+
client_id: str
|
|
60
|
+
client_secret: str
|
|
61
|
+
jwt_signing_key: str
|
|
62
|
+
allowed_ids: frozenset[str]
|
|
63
|
+
redirect_uris: tuple[str, ...] = (CLAUDE_CALLBACK,)
|
|
64
|
+
|
|
65
|
+
def __repr__(self) -> str:
|
|
66
|
+
return f"AuthSettings(allowed_ids={sorted(self.allowed_ids)})"
|
|
67
|
+
|
|
68
|
+
@classmethod
|
|
69
|
+
def from_env(
|
|
70
|
+
cls, server: Server, environ: Mapping[str, str] | None = None
|
|
71
|
+
) -> "AuthSettings | None":
|
|
72
|
+
"""Read sign-in settings, or None when none of them is set.
|
|
73
|
+
|
|
74
|
+
Some but not all set is a mistake, not "off": it is refused, naming what is
|
|
75
|
+
missing and never printing a value.
|
|
76
|
+
"""
|
|
77
|
+
env = os.environ if environ is None else environ
|
|
78
|
+
values = {name: env.get(server.var(name), "").strip() for name in REQUIRED}
|
|
79
|
+
if not any(values.values()):
|
|
80
|
+
return None
|
|
81
|
+
missing = [name for name, value in values.items() if not value]
|
|
82
|
+
if missing:
|
|
83
|
+
names = ", ".join(server.var(name) for name in missing)
|
|
84
|
+
raise ServeConfigError(f"sign-in is only partly configured: set {names}")
|
|
85
|
+
if len(values["JWT_SIGNING_KEY"]) < MIN_SIGNING_KEY_LENGTH:
|
|
86
|
+
raise ServeConfigError(
|
|
87
|
+
f"{server.var('JWT_SIGNING_KEY')} must be at least {MIN_SIGNING_KEY_LENGTH} "
|
|
88
|
+
"characters (for example: openssl rand -base64 32)"
|
|
89
|
+
)
|
|
90
|
+
redirect_var = server.var("OAUTH_REDIRECT_URIS")
|
|
91
|
+
redirect_raw = env.get(redirect_var, "").strip()
|
|
92
|
+
redirect_uris = tuple(_split(redirect_raw)) if redirect_raw else (CLAUDE_CALLBACK,)
|
|
93
|
+
for uri in redirect_uris:
|
|
94
|
+
if not uri.startswith("https://"):
|
|
95
|
+
raise ServeConfigError(f"{redirect_var} must be https URLs, got {uri!r}")
|
|
96
|
+
return cls(
|
|
97
|
+
client_id=values["GITHUB_CLIENT_ID"],
|
|
98
|
+
client_secret=values["GITHUB_CLIENT_SECRET"],
|
|
99
|
+
jwt_signing_key=values["JWT_SIGNING_KEY"],
|
|
100
|
+
allowed_ids=parse_github_ids(
|
|
101
|
+
values["ALLOWED_GITHUB_IDS"], name=server.var("ALLOWED_GITHUB_IDS")
|
|
102
|
+
),
|
|
103
|
+
redirect_uris=redirect_uris,
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _split(raw: str) -> list[str]:
|
|
108
|
+
return [part for part in re.split(r"[\s,]+", raw) if part]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def parse_github_ids(raw: str, *, name: str = "ALLOWED_GITHUB_IDS") -> frozenset[str]:
|
|
112
|
+
"""Parse the allow-list variable ``name``: numeric ids, comma- or space-separated."""
|
|
113
|
+
ids = _split(raw)
|
|
114
|
+
bad = [part for part in ids if not part.isdigit()]
|
|
115
|
+
if bad:
|
|
116
|
+
raise ServeConfigError(
|
|
117
|
+
f"{name} takes numeric GitHub user ids, not logins "
|
|
118
|
+
f"(find yours at https://api.github.com/users/<login>), got {', '.join(bad)}"
|
|
119
|
+
)
|
|
120
|
+
if not ids:
|
|
121
|
+
raise ServeConfigError(f"{name} lists no ids")
|
|
122
|
+
return frozenset(str(int(part)) for part in ids)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class AllowlistGitHubTokenVerifier(GitHubTokenVerifier):
|
|
126
|
+
"""A GitHub token verifier that accepts listed GitHub user ids only.
|
|
127
|
+
|
|
128
|
+
The parent verifies the token with GitHub and puts the numeric user id in the
|
|
129
|
+
``sub`` claim. Anyone not listed is treated like an invalid token: the request
|
|
130
|
+
gets 401 and no tool runs. GitHub being unreachable still raises the parent's
|
|
131
|
+
``TokenVerificationError``, which FastMCP answers as a temporary failure rather
|
|
132
|
+
than a sign-out.
|
|
133
|
+
"""
|
|
134
|
+
|
|
135
|
+
def __init__(
|
|
136
|
+
self,
|
|
137
|
+
*,
|
|
138
|
+
server: Server,
|
|
139
|
+
allowed_ids: frozenset[str],
|
|
140
|
+
required_scopes: list[str] | None = None,
|
|
141
|
+
cache_ttl_seconds: int | None = None,
|
|
142
|
+
http_client: httpx2.AsyncClient | None = None,
|
|
143
|
+
) -> None:
|
|
144
|
+
super().__init__(
|
|
145
|
+
required_scopes=required_scopes,
|
|
146
|
+
cache_ttl_seconds=cache_ttl_seconds,
|
|
147
|
+
http_client=http_client,
|
|
148
|
+
)
|
|
149
|
+
if not allowed_ids:
|
|
150
|
+
raise ValueError("allowed_ids must not be empty")
|
|
151
|
+
self.allowed_ids = frozenset(allowed_ids)
|
|
152
|
+
self._server = server
|
|
153
|
+
|
|
154
|
+
async def verify_token(self, token: str) -> AccessToken | None:
|
|
155
|
+
result = await super().verify_token(token)
|
|
156
|
+
if result is None:
|
|
157
|
+
return None
|
|
158
|
+
if not is_allowed(result, self.allowed_ids):
|
|
159
|
+
self._server.logger("auth").warning(
|
|
160
|
+
"refused GitHub account %s (id %s): not in %s",
|
|
161
|
+
result.claims.get("login"),
|
|
162
|
+
result.claims.get("sub"),
|
|
163
|
+
self._server.var("ALLOWED_GITHUB_IDS"),
|
|
164
|
+
)
|
|
165
|
+
return None
|
|
166
|
+
return result
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def is_allowed(token: AccessToken | None, allowed_ids: frozenset[str]) -> bool:
|
|
170
|
+
"""True if ``token`` belongs to a listed GitHub user id."""
|
|
171
|
+
if token is None:
|
|
172
|
+
return False
|
|
173
|
+
user_id = token.claims.get("sub")
|
|
174
|
+
return isinstance(user_id, str) and user_id in allowed_ids
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def allowlist_check(allowed_ids: frozenset[str]) -> "AllowlistCheck":
|
|
178
|
+
"""An ``AuthMiddleware`` check: the second layer behind the verifier."""
|
|
179
|
+
return AllowlistCheck(allowed_ids)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
@dataclass(frozen=True)
|
|
183
|
+
class AllowlistCheck:
|
|
184
|
+
"""Per-component check that the caller is a listed GitHub user.
|
|
185
|
+
|
|
186
|
+
The verifier already refuses everyone else at the HTTP layer; this runs again
|
|
187
|
+
for every tool, so a future change to how tokens are verified can't open the
|
|
188
|
+
tools by accident. FastMCP skips component checks on stdio, where there is no
|
|
189
|
+
sign-in.
|
|
190
|
+
"""
|
|
191
|
+
|
|
192
|
+
allowed_ids: frozenset[str]
|
|
193
|
+
|
|
194
|
+
def __call__(self, ctx: AuthContext) -> bool:
|
|
195
|
+
return is_allowed(ctx.token, self.allowed_ids)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def build_auth(
|
|
199
|
+
server: Server,
|
|
200
|
+
settings: AuthSettings,
|
|
201
|
+
public_url: str,
|
|
202
|
+
*,
|
|
203
|
+
client_storage: AsyncKeyValue | None = None,
|
|
204
|
+
github_http_client: httpx2.AsyncClient | None = None,
|
|
205
|
+
) -> OAuthProxy:
|
|
206
|
+
"""The OAuth proxy for HTTP mode: GitHub upstream, allowlisted verifier.
|
|
207
|
+
|
|
208
|
+
``client_storage`` and ``github_http_client`` exist for tests; in production
|
|
209
|
+
FastMCP's encrypted disk store and a real GitHub client are used.
|
|
210
|
+
"""
|
|
211
|
+
verifier = AllowlistGitHubTokenVerifier(
|
|
212
|
+
server=server,
|
|
213
|
+
allowed_ids=settings.allowed_ids,
|
|
214
|
+
required_scopes=GITHUB_SCOPES,
|
|
215
|
+
cache_ttl_seconds=VERIFY_CACHE_SECONDS,
|
|
216
|
+
http_client=github_http_client,
|
|
217
|
+
)
|
|
218
|
+
base_url = public_url.rstrip("/")
|
|
219
|
+
return OAuthProxy(
|
|
220
|
+
upstream_authorization_endpoint=GITHUB_AUTHORIZE_URL,
|
|
221
|
+
upstream_token_endpoint=GITHUB_TOKEN_URL,
|
|
222
|
+
upstream_client_id=settings.client_id,
|
|
223
|
+
upstream_client_secret=settings.client_secret,
|
|
224
|
+
token_verifier=verifier,
|
|
225
|
+
base_url=base_url,
|
|
226
|
+
issuer_url=base_url,
|
|
227
|
+
redirect_path=CALLBACK_PATH,
|
|
228
|
+
allowed_client_redirect_uris=list(settings.redirect_uris),
|
|
229
|
+
# An explicit key: the proxy's signing and storage keys derive from it, so
|
|
230
|
+
# rotating the GitHub client secret doesn't sign Claude out. FastMCP keeps
|
|
231
|
+
# registered clients in its own encrypted store on disk.
|
|
232
|
+
jwt_signing_key=settings.jwt_signing_key,
|
|
233
|
+
client_storage=client_storage,
|
|
234
|
+
require_authorization_consent=True,
|
|
235
|
+
)
|