fastmcp-events 4.2.6__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.
- fastmcp_events-4.2.6/.gitignore +83 -0
- fastmcp_events-4.2.6/PKG-INFO +61 -0
- fastmcp_events-4.2.6/README.md +35 -0
- fastmcp_events-4.2.6/fastmcp_events/__init__.py +79 -0
- fastmcp_events-4.2.6/fastmcp_events/_constants.py +9 -0
- fastmcp_events-4.2.6/fastmcp_events/cli.py +267 -0
- fastmcp_events-4.2.6/fastmcp_events/client.py +163 -0
- fastmcp_events-4.2.6/fastmcp_events/docket_log.py +196 -0
- fastmcp_events-4.2.6/fastmcp_events/extension.py +532 -0
- fastmcp_events-4.2.6/fastmcp_events/log.py +152 -0
- fastmcp_events-4.2.6/fastmcp_events/models.py +135 -0
- fastmcp_events-4.2.6/fastmcp_events/py.typed +0 -0
- fastmcp_events-4.2.6/fastmcp_events/registration.py +244 -0
- fastmcp_events-4.2.6/fastmcp_events/subscription.py +640 -0
- fastmcp_events-4.2.6/pyproject.toml +61 -0
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# Python-generated files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*$py.class
|
|
5
|
+
build/
|
|
6
|
+
dist/
|
|
7
|
+
wheels/
|
|
8
|
+
*.egg-info/
|
|
9
|
+
*.egg
|
|
10
|
+
MANIFEST
|
|
11
|
+
.pytest_cache/
|
|
12
|
+
.loq_cache
|
|
13
|
+
.coverage
|
|
14
|
+
htmlcov/
|
|
15
|
+
.tox/
|
|
16
|
+
nosetests.xml
|
|
17
|
+
coverage.xml
|
|
18
|
+
*.cover
|
|
19
|
+
|
|
20
|
+
# Virtual environments
|
|
21
|
+
.venv
|
|
22
|
+
venv/
|
|
23
|
+
env/
|
|
24
|
+
ENV/
|
|
25
|
+
.env
|
|
26
|
+
|
|
27
|
+
# System files
|
|
28
|
+
.DS_Store
|
|
29
|
+
|
|
30
|
+
# Version file
|
|
31
|
+
src/fastmcp/_version.py
|
|
32
|
+
|
|
33
|
+
# Editors and IDEs
|
|
34
|
+
.cursorrules
|
|
35
|
+
.vscode/
|
|
36
|
+
.idea/
|
|
37
|
+
*.swp
|
|
38
|
+
*.swo
|
|
39
|
+
*~
|
|
40
|
+
.project
|
|
41
|
+
.pydevproject
|
|
42
|
+
.settings/
|
|
43
|
+
|
|
44
|
+
# Jupyter Notebook
|
|
45
|
+
.ipynb_checkpoints
|
|
46
|
+
|
|
47
|
+
# Type checking
|
|
48
|
+
.mypy_cache/
|
|
49
|
+
.dmypy.json
|
|
50
|
+
dmypy.json
|
|
51
|
+
.pyre/
|
|
52
|
+
.pytype/
|
|
53
|
+
|
|
54
|
+
# Local development
|
|
55
|
+
.python-version
|
|
56
|
+
.envrc
|
|
57
|
+
.envrc.private
|
|
58
|
+
.direnv/
|
|
59
|
+
|
|
60
|
+
# Logs and databases
|
|
61
|
+
*.log
|
|
62
|
+
*.sqlite
|
|
63
|
+
*.db
|
|
64
|
+
*.ddb
|
|
65
|
+
|
|
66
|
+
# Claude worktree management
|
|
67
|
+
.claude-wt/worktrees
|
|
68
|
+
.claude/worktrees/
|
|
69
|
+
|
|
70
|
+
# Agents
|
|
71
|
+
/PLAN.md
|
|
72
|
+
/TODO.md
|
|
73
|
+
/STATUS.md
|
|
74
|
+
plans/
|
|
75
|
+
|
|
76
|
+
# Common FastMCP test files
|
|
77
|
+
/test.py
|
|
78
|
+
/server.py
|
|
79
|
+
/client.py
|
|
80
|
+
/test.json
|
|
81
|
+
|
|
82
|
+
# hypothesis example database (property-based test campaigns)
|
|
83
|
+
.hypothesis/
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: fastmcp-events
|
|
3
|
+
Version: 4.2.6
|
|
4
|
+
Summary: Events for FastMCP servers and clients via the io.modelcontextprotocol/events extension (SEP-3415).
|
|
5
|
+
Project-URL: Homepage, https://gofastmcp.com
|
|
6
|
+
Project-URL: Repository, https://github.com/PrefectHQ/fastmcp
|
|
7
|
+
Project-URL: Documentation, https://gofastmcp.com
|
|
8
|
+
Author: Jeremiah Lowin, Nate Nowack
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
Keywords: events,fastmcp,fastmcp events,mcp,model context protocol
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.11
|
|
21
|
+
Requires-Dist: fastmcp-slim[mcp]==4.2.6
|
|
22
|
+
Provides-Extra: docket
|
|
23
|
+
Requires-Dist: pydocket>=0.29.1; extra == 'docket'
|
|
24
|
+
Requires-Dist: redis!=8.1.0; extra == 'docket'
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# fastmcp-events
|
|
28
|
+
|
|
29
|
+
Events for FastMCP servers and clients: the `io.modelcontextprotocol/events` extension defined in [SEP-3415](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/3415), with poll and push delivery.
|
|
30
|
+
|
|
31
|
+
Experimental: the API may change in any release without a deprecation period.
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install "fastmcp[events]"
|
|
35
|
+
# with the Redis-backed log, through Docket
|
|
36
|
+
pip install "fastmcp[events]" "fastmcp-events[docket]"
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
from pydantic import BaseModel
|
|
41
|
+
|
|
42
|
+
from fastmcp import FastMCP
|
|
43
|
+
from fastmcp_events import EventsExtension
|
|
44
|
+
|
|
45
|
+
mcp = FastMCP("alerts")
|
|
46
|
+
events = EventsExtension()
|
|
47
|
+
mcp.add_extension(events)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@events.event("alert.fired")
|
|
51
|
+
class AlertFired(BaseModel):
|
|
52
|
+
"""An alert fired."""
|
|
53
|
+
|
|
54
|
+
project: str
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
# later, in a tool or webhook handler:
|
|
58
|
+
# await events.emit(AlertFired(project="api"))
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
See the [Events docs](https://gofastmcp.com/servers/events).
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# fastmcp-events
|
|
2
|
+
|
|
3
|
+
Events for FastMCP servers and clients: the `io.modelcontextprotocol/events` extension defined in [SEP-3415](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/3415), with poll and push delivery.
|
|
4
|
+
|
|
5
|
+
Experimental: the API may change in any release without a deprecation period.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install "fastmcp[events]"
|
|
9
|
+
# with the Redis-backed log, through Docket
|
|
10
|
+
pip install "fastmcp[events]" "fastmcp-events[docket]"
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from pydantic import BaseModel
|
|
15
|
+
|
|
16
|
+
from fastmcp import FastMCP
|
|
17
|
+
from fastmcp_events import EventsExtension
|
|
18
|
+
|
|
19
|
+
mcp = FastMCP("alerts")
|
|
20
|
+
events = EventsExtension()
|
|
21
|
+
mcp.add_extension(events)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@events.event("alert.fired")
|
|
25
|
+
class AlertFired(BaseModel):
|
|
26
|
+
"""An alert fired."""
|
|
27
|
+
|
|
28
|
+
project: str
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# later, in a tool or webhook handler:
|
|
32
|
+
# await events.emit(AlertFired(project="api"))
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
See the [Events docs](https://gofastmcp.com/servers/events).
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Protocol support for the MCP Events extension (SEP-3415).
|
|
2
|
+
|
|
3
|
+
Experimental: this API may change in any release without a deprecation period.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from typing import TYPE_CHECKING
|
|
7
|
+
|
|
8
|
+
from fastmcp_events.models import (
|
|
9
|
+
EventOccurrence,
|
|
10
|
+
EventType,
|
|
11
|
+
ListEventsResult,
|
|
12
|
+
PollEventsResult,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"Event",
|
|
17
|
+
"EventBacklogFullError",
|
|
18
|
+
"EventBatch",
|
|
19
|
+
"EventOccurrence",
|
|
20
|
+
"EventPoll",
|
|
21
|
+
"EventSubscription",
|
|
22
|
+
"EventType",
|
|
23
|
+
"EventsClientExtension",
|
|
24
|
+
"EventsExtension",
|
|
25
|
+
"ListEventsResult",
|
|
26
|
+
"PollEventsResult",
|
|
27
|
+
"list_events",
|
|
28
|
+
"list_events_mcp",
|
|
29
|
+
"poll_events_mcp",
|
|
30
|
+
"subscribe_events",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
_LAZY = {
|
|
34
|
+
"Event": "fastmcp_events.extension",
|
|
35
|
+
"EventBacklogFullError": "fastmcp_events.subscription",
|
|
36
|
+
"EventBatch": "fastmcp_events.extension",
|
|
37
|
+
"EventPoll": "fastmcp_events.extension",
|
|
38
|
+
"EventsExtension": "fastmcp_events.extension",
|
|
39
|
+
"EventsClientExtension": "fastmcp_events.client",
|
|
40
|
+
"EventSubscription": "fastmcp_events.subscription",
|
|
41
|
+
"list_events": "fastmcp_events.subscription",
|
|
42
|
+
"list_events_mcp": "fastmcp_events.subscription",
|
|
43
|
+
"poll_events_mcp": "fastmcp_events.subscription",
|
|
44
|
+
"subscribe_events": "fastmcp_events.subscription",
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if TYPE_CHECKING:
|
|
48
|
+
from fastmcp_events.subscription import (
|
|
49
|
+
EventBacklogFullError as EventBacklogFullError,
|
|
50
|
+
)
|
|
51
|
+
from fastmcp_events.subscription import (
|
|
52
|
+
EventSubscription as EventSubscription,
|
|
53
|
+
)
|
|
54
|
+
from fastmcp_events.subscription import list_events as list_events
|
|
55
|
+
from fastmcp_events.subscription import (
|
|
56
|
+
list_events_mcp as list_events_mcp,
|
|
57
|
+
)
|
|
58
|
+
from fastmcp_events.subscription import (
|
|
59
|
+
poll_events_mcp as poll_events_mcp,
|
|
60
|
+
)
|
|
61
|
+
from fastmcp_events.subscription import (
|
|
62
|
+
subscribe_events as subscribe_events,
|
|
63
|
+
)
|
|
64
|
+
from fastmcp_events.client import (
|
|
65
|
+
EventsClientExtension as EventsClientExtension,
|
|
66
|
+
)
|
|
67
|
+
from fastmcp_events.extension import Event as Event
|
|
68
|
+
from fastmcp_events.extension import EventBatch as EventBatch
|
|
69
|
+
from fastmcp_events.extension import EventPoll as EventPoll
|
|
70
|
+
from fastmcp_events.extension import EventsExtension as EventsExtension
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def __getattr__(name: str) -> object:
|
|
74
|
+
module = _LAZY.get(name)
|
|
75
|
+
if module is None:
|
|
76
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
77
|
+
import importlib
|
|
78
|
+
|
|
79
|
+
return getattr(importlib.import_module(module), name)
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Shared constants for the MCP Events extension."""
|
|
2
|
+
|
|
3
|
+
EVENTS_EXTENSION_ID = "io.modelcontextprotocol/events"
|
|
4
|
+
|
|
5
|
+
# Error codes SEP-3415 allocates in the specification's range.
|
|
6
|
+
NOT_FOUND = -32023
|
|
7
|
+
FORBIDDEN = -32024
|
|
8
|
+
RESOURCE_EXHAUSTED = -32025
|
|
9
|
+
UNSUPPORTED = -32026
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
"""`fastmcp experimental events`: list a server's event types and watch one as it fires.
|
|
2
|
+
|
|
3
|
+
Experimental: this command may change in any release without a deprecation period.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from contextlib import aclosing
|
|
9
|
+
from typing import Annotated, Any, Literal
|
|
10
|
+
|
|
11
|
+
import cyclopts
|
|
12
|
+
from rich.console import Console
|
|
13
|
+
|
|
14
|
+
from fastmcp.cli import client as client_cli
|
|
15
|
+
from fastmcp_events import list_events, subscribe_events
|
|
16
|
+
from fastmcp_events.models import EventOccurrence, EventType
|
|
17
|
+
|
|
18
|
+
console = Console()
|
|
19
|
+
# Status lines go to stderr so `watch --json` output stays one event per line.
|
|
20
|
+
status = Console(stderr=True)
|
|
21
|
+
|
|
22
|
+
events_app = cyclopts.App(
|
|
23
|
+
name="events",
|
|
24
|
+
help="Subscribe to a server's events (the MCP Events extension, SEP-3415)",
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
ServerSpec = Annotated[
|
|
28
|
+
str | None,
|
|
29
|
+
cyclopts.Parameter(help="Server URL, Python file, MCPConfig JSON, or .js file"),
|
|
30
|
+
]
|
|
31
|
+
Command = Annotated[
|
|
32
|
+
str | None,
|
|
33
|
+
cyclopts.Parameter(
|
|
34
|
+
"--command", help="Stdio command to connect to (e.g. 'npx -y @mcp/server')"
|
|
35
|
+
),
|
|
36
|
+
]
|
|
37
|
+
Transport = Annotated[
|
|
38
|
+
Literal["http", "sse"] | None,
|
|
39
|
+
cyclopts.Parameter(
|
|
40
|
+
name=["--transport", "-t"],
|
|
41
|
+
help="Force transport type for URL targets (http or sse)",
|
|
42
|
+
),
|
|
43
|
+
]
|
|
44
|
+
Timeout = Annotated[
|
|
45
|
+
float | None,
|
|
46
|
+
cyclopts.Parameter("--timeout", help="Connection timeout in seconds"),
|
|
47
|
+
]
|
|
48
|
+
Auth = Annotated[
|
|
49
|
+
str | None,
|
|
50
|
+
cyclopts.Parameter(
|
|
51
|
+
"--auth",
|
|
52
|
+
help="Auth method: 'oauth', a bearer token string, or 'none' to disable",
|
|
53
|
+
),
|
|
54
|
+
]
|
|
55
|
+
JsonOutput = Annotated[bool, cyclopts.Parameter("--json", help="Output JSON")]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _fail(message: str) -> None:
|
|
59
|
+
console.print(f"[bold red]Error:[/bold red] {message}")
|
|
60
|
+
sys.exit(1)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _require_events(client: Any) -> None:
|
|
64
|
+
capabilities = client.server_capabilities
|
|
65
|
+
extensions = capabilities.extensions if capabilities else None
|
|
66
|
+
if not extensions or "io.modelcontextprotocol/events" not in extensions:
|
|
67
|
+
_fail("The server does not advertise the Events extension")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
# Everything below that comes from the server is untrusted terminal output.
|
|
71
|
+
_safe = client_cli._sanitize_untrusted_text
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _describe(event_type: EventType) -> None:
|
|
75
|
+
delivery = ", ".join(event_type.delivery)
|
|
76
|
+
console.print(f" [cyan]{_safe(event_type.name)}[/cyan] [dim]({delivery})[/dim]")
|
|
77
|
+
if event_type.description:
|
|
78
|
+
console.print(f" {_safe(event_type.description)}")
|
|
79
|
+
properties = (event_type.input_schema or {}).get("properties") or {}
|
|
80
|
+
for name, schema in properties.items():
|
|
81
|
+
kind = client_cli._json_schema_type_to_str(schema)
|
|
82
|
+
console.print(f" [dim]{_safe(name)}: {_safe(str(kind))}[/dim]")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@events_app.command(name="list")
|
|
86
|
+
async def list_events_command(
|
|
87
|
+
server_spec: ServerSpec = None,
|
|
88
|
+
*,
|
|
89
|
+
command: Command = None,
|
|
90
|
+
transport: Transport = None,
|
|
91
|
+
json_output: JsonOutput = False,
|
|
92
|
+
timeout: Timeout = None,
|
|
93
|
+
auth: Auth = None,
|
|
94
|
+
) -> None:
|
|
95
|
+
"""List the event types a server offers.
|
|
96
|
+
|
|
97
|
+
Examples:
|
|
98
|
+
```
|
|
99
|
+
fastmcp experimental events list server.py
|
|
100
|
+
fastmcp experimental events list http://localhost:8000/mcp --json
|
|
101
|
+
```
|
|
102
|
+
"""
|
|
103
|
+
resolved = client_cli.resolve_server_spec(
|
|
104
|
+
server_spec, command=command, transport=transport
|
|
105
|
+
)
|
|
106
|
+
try:
|
|
107
|
+
client = client_cli._build_client(
|
|
108
|
+
resolved, timeout=timeout, auth=auth, events=True
|
|
109
|
+
)
|
|
110
|
+
async with client:
|
|
111
|
+
_require_events(client)
|
|
112
|
+
event_types = await list_events(client)
|
|
113
|
+
except Exception as exc:
|
|
114
|
+
_fail(_safe(str(exc)))
|
|
115
|
+
return
|
|
116
|
+
|
|
117
|
+
if json_output:
|
|
118
|
+
listing = [
|
|
119
|
+
event_type.model_dump(mode="json", by_alias=True, exclude_none=True)
|
|
120
|
+
for event_type in event_types
|
|
121
|
+
]
|
|
122
|
+
print(json.dumps({"events": listing}, indent=2))
|
|
123
|
+
return
|
|
124
|
+
console.print(f"[bold]Events ({len(event_types)})[/bold]")
|
|
125
|
+
for event_type in event_types:
|
|
126
|
+
_describe(event_type)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _print_occurrence(event: EventOccurrence, cursor: str | None) -> None:
|
|
130
|
+
console.print(
|
|
131
|
+
f"[green]{_safe(event.timestamp)}[/green] "
|
|
132
|
+
f"[cyan]{_safe(event.name)}[/cyan] {_safe(event.event_id)}"
|
|
133
|
+
)
|
|
134
|
+
payload = json.dumps(event.data, indent=2, ensure_ascii=False)
|
|
135
|
+
console.print(_safe(payload), highlight=False)
|
|
136
|
+
if cursor is not None:
|
|
137
|
+
console.print(f"[dim]cursor {_safe(cursor)}[/dim]", highlight=False)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@events_app.command(name="watch")
|
|
141
|
+
async def watch_command(
|
|
142
|
+
server_spec: ServerSpec = None,
|
|
143
|
+
name: Annotated[str, cyclopts.Parameter(help="Event type to subscribe to")] = "",
|
|
144
|
+
*arguments: str,
|
|
145
|
+
command: Command = None,
|
|
146
|
+
transport: Transport = None,
|
|
147
|
+
input_json: Annotated[
|
|
148
|
+
str | None,
|
|
149
|
+
cyclopts.Parameter(
|
|
150
|
+
"--input-json",
|
|
151
|
+
help="JSON object of subscription arguments (merged with key=value args)",
|
|
152
|
+
),
|
|
153
|
+
] = None,
|
|
154
|
+
cursor: Annotated[
|
|
155
|
+
str | None,
|
|
156
|
+
cyclopts.Parameter(
|
|
157
|
+
"--cursor", help="Resume from this cursor instead of starting from now"
|
|
158
|
+
),
|
|
159
|
+
] = None,
|
|
160
|
+
max_age: Annotated[
|
|
161
|
+
float | None,
|
|
162
|
+
cyclopts.Parameter(
|
|
163
|
+
"--max-age", help="With --cursor, replay at most this many seconds"
|
|
164
|
+
),
|
|
165
|
+
] = None,
|
|
166
|
+
delivery: Annotated[
|
|
167
|
+
Literal["poll", "push"] | None,
|
|
168
|
+
cyclopts.Parameter(
|
|
169
|
+
"--delivery", help="Force poll or push (default: push when offered)"
|
|
170
|
+
),
|
|
171
|
+
] = None,
|
|
172
|
+
count: Annotated[
|
|
173
|
+
int | None,
|
|
174
|
+
cyclopts.Parameter("--count", help="Exit after this many events"),
|
|
175
|
+
] = None,
|
|
176
|
+
min_poll_interval: Annotated[
|
|
177
|
+
float,
|
|
178
|
+
cyclopts.Parameter(
|
|
179
|
+
"--min-poll-interval", help="Shortest wait between polls, in seconds"
|
|
180
|
+
),
|
|
181
|
+
] = 1.0,
|
|
182
|
+
json_output: Annotated[
|
|
183
|
+
bool,
|
|
184
|
+
cyclopts.Parameter("--json", help="Print one JSON object per event"),
|
|
185
|
+
] = False,
|
|
186
|
+
timeout: Timeout = None,
|
|
187
|
+
auth: Auth = None,
|
|
188
|
+
) -> None:
|
|
189
|
+
"""Subscribe to an event type and print each event as it arrives.
|
|
190
|
+
|
|
191
|
+
Arguments are key=value pairs, coerced with the event type's input
|
|
192
|
+
schema. The watch runs until interrupted (or `--count` events), then
|
|
193
|
+
prints the cursor to resume from.
|
|
194
|
+
|
|
195
|
+
Examples:
|
|
196
|
+
```
|
|
197
|
+
fastmcp experimental events watch server.py alert.fired
|
|
198
|
+
fastmcp experimental events watch server.py alert.fired severity=P1 --json
|
|
199
|
+
fastmcp experimental events watch http://localhost:8000/mcp alert.fired --cursor 42
|
|
200
|
+
```
|
|
201
|
+
"""
|
|
202
|
+
if not name:
|
|
203
|
+
_fail(
|
|
204
|
+
"Missing event name.\n\n"
|
|
205
|
+
"Usage: fastmcp experimental events watch <server> <event> [key=value ...]\n\n"
|
|
206
|
+
"Use [cyan]fastmcp experimental events list <server>[/cyan] to see event types."
|
|
207
|
+
)
|
|
208
|
+
resolved = client_cli.resolve_server_spec(
|
|
209
|
+
server_spec, command=command, transport=transport
|
|
210
|
+
)
|
|
211
|
+
subscription = None
|
|
212
|
+
seen = 0
|
|
213
|
+
try:
|
|
214
|
+
client = client_cli._build_client(
|
|
215
|
+
resolved, timeout=timeout, auth=auth, events=True
|
|
216
|
+
)
|
|
217
|
+
async with client:
|
|
218
|
+
_require_events(client)
|
|
219
|
+
event_types = {t.name: t for t in await list_events(client)}
|
|
220
|
+
event_type = event_types.get(name)
|
|
221
|
+
if event_type is None:
|
|
222
|
+
available = ", ".join(_safe(t) for t in sorted(event_types))
|
|
223
|
+
_fail(
|
|
224
|
+
f"Unknown event [cyan]{_safe(name)}[/cyan]. "
|
|
225
|
+
f"Available: {available or 'none'}"
|
|
226
|
+
)
|
|
227
|
+
return
|
|
228
|
+
subscription_args = client_cli.parse_tool_arguments(
|
|
229
|
+
arguments, input_json, event_type.input_schema or {}
|
|
230
|
+
)
|
|
231
|
+
subscription = subscribe_events(
|
|
232
|
+
client,
|
|
233
|
+
name,
|
|
234
|
+
subscription_args or None,
|
|
235
|
+
cursor=cursor,
|
|
236
|
+
max_age_ms=None if max_age is None else int(max_age * 1000),
|
|
237
|
+
min_poll_interval=min_poll_interval,
|
|
238
|
+
delivery=delivery,
|
|
239
|
+
)
|
|
240
|
+
status.print(f"[dim]watching {name}; Ctrl-C to stop[/dim]")
|
|
241
|
+
async with aclosing(subscription.__aiter__()) as events:
|
|
242
|
+
async for event in events:
|
|
243
|
+
seen += 1
|
|
244
|
+
if json_output:
|
|
245
|
+
record = event.model_dump(
|
|
246
|
+
mode="json", by_alias=True, exclude_none=True
|
|
247
|
+
)
|
|
248
|
+
print(json.dumps({**record, "cursor": subscription.cursor}))
|
|
249
|
+
sys.stdout.flush()
|
|
250
|
+
else:
|
|
251
|
+
_print_occurrence(event, subscription.cursor)
|
|
252
|
+
if count is not None and seen >= count:
|
|
253
|
+
break
|
|
254
|
+
except KeyboardInterrupt:
|
|
255
|
+
pass
|
|
256
|
+
except Exception as exc:
|
|
257
|
+
_fail(_safe(str(exc)))
|
|
258
|
+
finally:
|
|
259
|
+
if subscription is not None:
|
|
260
|
+
if subscription.truncated:
|
|
261
|
+
status.print("[yellow]The server skipped events (truncated)[/yellow]")
|
|
262
|
+
if subscription.cursor is not None:
|
|
263
|
+
status.print(
|
|
264
|
+
f"[dim]{seen} event(s); resume with --cursor "
|
|
265
|
+
f"{_safe(subscription.cursor)}[/dim]",
|
|
266
|
+
highlight=False,
|
|
267
|
+
)
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""Client side of the MCP Events extension: the capability and push routing.
|
|
2
|
+
|
|
3
|
+
Experimental: this API may change in any release without a deprecation period.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
9
|
+
from functools import partial
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
import anyio
|
|
13
|
+
from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream
|
|
14
|
+
from mcp.client.extension import ClientExtension, NotificationBinding
|
|
15
|
+
from mcp.shared.subscriptions import SUBSCRIPTION_ID_META_KEY
|
|
16
|
+
from mcp_types import RequestId
|
|
17
|
+
from pydantic import ValidationError
|
|
18
|
+
|
|
19
|
+
from fastmcp.utilities.logging import get_logger
|
|
20
|
+
from fastmcp_events._constants import EVENTS_EXTENSION_ID
|
|
21
|
+
from fastmcp_events.models import StreamFrame
|
|
22
|
+
|
|
23
|
+
logger = get_logger(__name__)
|
|
24
|
+
|
|
25
|
+
_STREAM_KINDS = ("active", "event", "heartbeat", "error", "terminated")
|
|
26
|
+
_STREAM_METHOD_PREFIX = "notifications/events/"
|
|
27
|
+
_MAX_PENDING_FRAMES = 1024
|
|
28
|
+
|
|
29
|
+
#: One `notifications/events/*` message: its kind and its params.
|
|
30
|
+
Frame = tuple[str, StreamFrame]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class _OrderedIntercept:
|
|
34
|
+
"""A dispatcher's notification intercept, with Events routing in front."""
|
|
35
|
+
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
extension: EventsClientExtension,
|
|
39
|
+
previous: Callable[[str, Mapping[str, Any] | None], bool] | None,
|
|
40
|
+
) -> None:
|
|
41
|
+
self.extension = extension
|
|
42
|
+
self.previous = previous
|
|
43
|
+
|
|
44
|
+
def __call__(self, method: str, params: Mapping[str, Any] | None) -> bool:
|
|
45
|
+
if self.extension._route_in_order(method, params):
|
|
46
|
+
return True
|
|
47
|
+
return self.previous(method, params) if self.previous is not None else False
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class EventsClientExtension(ClientExtension):
|
|
51
|
+
"""Declare support for the SEP-3415 Events extension.
|
|
52
|
+
|
|
53
|
+
Experimental: this API may change in any release without a deprecation
|
|
54
|
+
period.
|
|
55
|
+
|
|
56
|
+
The instance also routes push notifications to the `events/stream` request
|
|
57
|
+
they belong to, so use one instance per `Client`.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
identifier = EVENTS_EXTENSION_ID
|
|
61
|
+
|
|
62
|
+
def __init__(self) -> None:
|
|
63
|
+
self._streams: dict[RequestId, MemoryObjectSendStream[Frame]] = {}
|
|
64
|
+
# Per stream: stops the `events/stream` request when its buffer fills.
|
|
65
|
+
self._stoppers: dict[RequestId, Callable[[], None]] = {}
|
|
66
|
+
# Streams ended because their consumer fell behind.
|
|
67
|
+
self._overflowed: set[RequestId] = set()
|
|
68
|
+
# Per event name: argument path -> x-mcp-header token, from events/list.
|
|
69
|
+
self._header_maps: dict[str, dict[tuple[str, ...], str]] = {}
|
|
70
|
+
|
|
71
|
+
def notifications(self) -> Sequence[NotificationBinding[Any]]:
|
|
72
|
+
# The fallback for a session `_attach` could not hook: the SDK queues
|
|
73
|
+
# each method separately, so frames of different kinds can arrive here
|
|
74
|
+
# out of wire order.
|
|
75
|
+
return [
|
|
76
|
+
NotificationBinding(
|
|
77
|
+
method=f"{_STREAM_METHOD_PREFIX}{kind}",
|
|
78
|
+
params_type=StreamFrame,
|
|
79
|
+
handler=partial(self._route_bound, kind),
|
|
80
|
+
)
|
|
81
|
+
for kind in _STREAM_KINDS
|
|
82
|
+
]
|
|
83
|
+
|
|
84
|
+
def _attach(self, dispatcher: Any) -> None:
|
|
85
|
+
"""Route stream frames on `dispatcher`'s receive path, in wire order.
|
|
86
|
+
|
|
87
|
+
The SDK delivers each notification method through its own queue and
|
|
88
|
+
task, so a heartbeat can overtake the events sent before it, and its
|
|
89
|
+
cursor would then skip them. The dispatcher's notification intercept
|
|
90
|
+
runs synchronously in receive order, as the SDK's own
|
|
91
|
+
`subscriptions/listen` routing relies on.
|
|
92
|
+
"""
|
|
93
|
+
if not hasattr(dispatcher, "_on_notify_intercept"):
|
|
94
|
+
logger.warning(
|
|
95
|
+
"This MCP SDK offers no notification intercept; push frames of "
|
|
96
|
+
"different kinds may arrive out of order"
|
|
97
|
+
)
|
|
98
|
+
return
|
|
99
|
+
previous = dispatcher._on_notify_intercept
|
|
100
|
+
if isinstance(previous, _OrderedIntercept) and previous.extension is self:
|
|
101
|
+
return
|
|
102
|
+
dispatcher._on_notify_intercept = _OrderedIntercept(self, previous)
|
|
103
|
+
|
|
104
|
+
def _route_in_order(self, method: str, params: Mapping[str, Any] | None) -> bool:
|
|
105
|
+
"""Route a frame for an open stream; leave anything else to the SDK."""
|
|
106
|
+
kind = method.removeprefix(_STREAM_METHOD_PREFIX)
|
|
107
|
+
if kind == method or kind not in _STREAM_KINDS or params is None:
|
|
108
|
+
return False
|
|
109
|
+
meta = params.get("_meta")
|
|
110
|
+
if not isinstance(meta, Mapping):
|
|
111
|
+
return False
|
|
112
|
+
subscription_id = meta.get(SUBSCRIPTION_ID_META_KEY)
|
|
113
|
+
if not isinstance(subscription_id, str | int) or (
|
|
114
|
+
subscription_id not in self._streams
|
|
115
|
+
):
|
|
116
|
+
return False
|
|
117
|
+
try:
|
|
118
|
+
frame = StreamFrame.model_validate(params)
|
|
119
|
+
except ValidationError:
|
|
120
|
+
return False
|
|
121
|
+
self._route(kind, frame)
|
|
122
|
+
return True
|
|
123
|
+
|
|
124
|
+
def _open(
|
|
125
|
+
self, subscription_id: RequestId, stop: Callable[[], None]
|
|
126
|
+
) -> MemoryObjectReceiveStream[Frame]:
|
|
127
|
+
send, receive = anyio.create_memory_object_stream[Frame](_MAX_PENDING_FRAMES)
|
|
128
|
+
self._streams[subscription_id] = send
|
|
129
|
+
self._stoppers[subscription_id] = stop
|
|
130
|
+
return receive
|
|
131
|
+
|
|
132
|
+
def _close(self, subscription_id: RequestId) -> None:
|
|
133
|
+
self._stoppers.pop(subscription_id, None)
|
|
134
|
+
send = self._streams.pop(subscription_id, None)
|
|
135
|
+
if send is not None:
|
|
136
|
+
send.close()
|
|
137
|
+
|
|
138
|
+
def _take_overflow(self, subscription_id: RequestId) -> bool:
|
|
139
|
+
"""Whether the stream ended because its backlog filled up."""
|
|
140
|
+
if subscription_id in self._overflowed:
|
|
141
|
+
self._overflowed.discard(subscription_id)
|
|
142
|
+
return True
|
|
143
|
+
return False
|
|
144
|
+
|
|
145
|
+
async def _route_bound(self, kind: str, frame: StreamFrame) -> None:
|
|
146
|
+
self._route(kind, frame)
|
|
147
|
+
|
|
148
|
+
def _route(self, kind: str, frame: StreamFrame) -> None:
|
|
149
|
+
send = self._streams.get(frame.meta.get(SUBSCRIPTION_ID_META_KEY))
|
|
150
|
+
if send is None:
|
|
151
|
+
return
|
|
152
|
+
try:
|
|
153
|
+
send.send_nowait((kind, frame))
|
|
154
|
+
except anyio.WouldBlock:
|
|
155
|
+
logger.warning("Event stream backlog is full; ending the subscription")
|
|
156
|
+
subscription_id = frame.meta[SUBSCRIPTION_ID_META_KEY]
|
|
157
|
+
self._overflowed.add(subscription_id)
|
|
158
|
+
stop = self._stoppers.get(subscription_id)
|
|
159
|
+
self._close(subscription_id)
|
|
160
|
+
if stop is not None:
|
|
161
|
+
stop()
|
|
162
|
+
except anyio.ClosedResourceError:
|
|
163
|
+
pass
|