@941design/nostr-mcp 0.0.0-stage → 0.1.0-alpha.1
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.
- package/CHANGELOG.md +13 -0
- package/LICENSE +21 -0
- package/README.md +283 -2
- package/dist/advanced.d.ts +160 -0
- package/dist/advanced.js +821 -0
- package/dist/authority.d.ts +131 -0
- package/dist/authority.js +434 -0
- package/dist/cli-diagnostics.d.ts +2 -0
- package/dist/cli-diagnostics.js +40 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +39 -0
- package/dist/config.d.ts +43 -0
- package/dist/config.js +266 -0
- package/dist/http.d.ts +30 -0
- package/dist/http.js +748 -0
- package/dist/index.d.ts +46 -0
- package/dist/index.js +816 -0
- package/dist/publish.d.ts +32 -0
- package/dist/publish.js +206 -0
- package/dist/schemas.d.ts +480 -0
- package/dist/schemas.js +217 -0
- package/package.json +52 -3
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# @941design/nostr-mcp
|
|
2
|
+
|
|
3
|
+
## 0.1.0-alpha.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- c6d8ba5: Add portable bounded relay reads and an optional read-only local MCP adapter with configured relay policy, resource budgets, cancellation and explicit partial-result metadata. Add installed-package browser and Node runtime verification.
|
|
8
|
+
- 2b74bb8: Add opt-in signed publication, injected signer/private-message capabilities and operator NIP-46 enrollment. Add durable bounded cursor snapshots, live subscription handles and authenticated multi-user HTTP hosting with explicit authority and lifecycle controls. Read-only stdio defaults are preserved.
|
|
9
|
+
- abb1432: Reject batch and malformed HTTP messages before dispatch, bound pending work per session and principal, and preserve sessions across fetch disconnects. Continue inbox processing after ambiguous remote decrypt failures and report them separately. Repair cursor bookkeeping after failed cleanup, handle argument-free WebSocket errors, and preserve enrollment input error codes.
|
|
10
|
+
- 0362cac: Fix HTTP request-slot exhaustion, preserve partial results across read deadlines, and make configured relay defaults usable. Improve cursor-store fairness, signer lookup and budget handling, relay authentication retries, transport metadata forwarding and safe CLI diagnostics. Account bounded read responses incrementally and clarify bounded subscription and NIP-59 delivery semantics.
|
|
11
|
+
- Updated dependencies [c6d8ba5]
|
|
12
|
+
- Updated dependencies [0362cac]
|
|
13
|
+
- @941design/nostr-events@0.2.0-alpha.1
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Markus Rother
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,284 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @941design/nostr-mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
MCP adapter for `@941design/nostr-events` with read-only defaults and separately authorized publishing, identity and hosted capabilities. Built ESM and types require Node >=22. Browser applications use the core package directly; MCP and Node dependencies remain in this adapter. Without additional trusted configuration, only the two public read tools are registered.
|
|
4
|
+
|
|
5
|
+
Install with `pnpm add @941design/nostr-mcp nostr-tools`. Put trusted startup settings in a JSON file:
|
|
6
|
+
|
|
7
|
+
```json
|
|
8
|
+
{
|
|
9
|
+
"relays": {"fixture": "ws://127.0.0.1:7447"},
|
|
10
|
+
"allowLocalRelays": true
|
|
11
|
+
}
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
`allowLocalRelays` is a development opt-in; production defaults require secure public relay destinations. Configured identifiers are the only relay selectors accepted by tools. When no subset is supplied, calls use the first `maxRelaysPerCall` configured identifiers in configuration order; publication applies the same rule within its configured relay subset. Selection is deterministic, not rotating: to contact all eight configured relays, set `maxRelaysPerCall: 8` or explicitly choose a permitted subset. Explicit oversized selections are rejected before networking or signer work. Credentials and fragments are rejected. Redirects are disabled, and DNS results are checked before connection. A factory instance represents one configured principal. Stdio uses that principal directly; the optional HTTP host authenticates and isolates remote sessions. No network listener or identity provider is started by the stdio command.
|
|
15
|
+
|
|
16
|
+
Start with `nostr-mcp /absolute/path/config.json`. An MCP host configuration looks like:
|
|
17
|
+
|
|
18
|
+
```json
|
|
19
|
+
{"mcpServers":{"nostr":{"command":"nostr-mcp","args":["/absolute/path/config.json"]}}}
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
The fixture relay is supplied by `fixtures/runtime/probe.mjs` in the repository; it needs no public service or real account. Stdout is reserved for protocol messages. Startup failures write safe usage, structural configuration paths or filesystem error codes to stderr, without echoing configuration values or raw exceptions. EOF, SIGINT, and SIGTERM stop admission, cancel owned work, and close the server.
|
|
23
|
+
|
|
24
|
+
For embedding:
|
|
25
|
+
|
|
26
|
+
```js
|
|
27
|
+
import { createNostrMcpServer } from '@941design/nostr-mcp';
|
|
28
|
+
const app = createNostrMcpServer({
|
|
29
|
+
relays: { fixture: 'ws://127.0.0.1:7447' },
|
|
30
|
+
allowLocalRelays: true,
|
|
31
|
+
});
|
|
32
|
+
// Connect an SDK transport with await app.server.connect(transport).
|
|
33
|
+
// execute also enforces the same tool schema, budgets and relay policy:
|
|
34
|
+
const result = await app.execute('nostr_query_events', {filter: {kinds: [1]}});
|
|
35
|
+
await app.shutdown();
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
The factory installs no process handlers and opens no sockets until a read starts. Shutdown is asynchronous and idempotent. Each read owns its sockets; cancellation closes only that read. Shared third-party transports/pools are not accepted because they cannot provide the required ingress guarantees. Existing core pool ownership semantics remain available to direct core consumers.
|
|
39
|
+
|
|
40
|
+
Tools are `nostr_query_events` (`filter`, optional `relays`, `limit`, `timeoutMs`) and `nostr_get_event` (`id`, optional `relays`, `timeoutMs`). Filter keys are full hexadecimal `ids`/`authors`, `kinds`, `since`, `until`, `limit`, and single-letter `#a`–`#z`/`#A`–`#Z` tags. Empty filters are bounded; selector arrays must be nonempty. Prefixes, `search`, unknown properties, and invalid ranges are rejected. Full hexadecimal inputs normalize to lowercase. The effective event limit is the minimum of the configured, tool, and filter limits; requests above the configured ceiling fail before connecting.
|
|
41
|
+
|
|
42
|
+
`inputSchemas` and `outputSchemas` export the public finite-read JSON schemas; every enabled tool advertises its operation-specific input/output schemas to MCP clients. Successful results carry equivalent structured output and textual JSON. Envelope version `schemaVersion: "1"` includes verified matching events (or exact `event`/null), effective limits, metrics, per-relay statuses, and provenance limited to returned events and configured identifiers. Content is untrusted event data.
|
|
43
|
+
|
|
44
|
+
`coverage` is always `"unknown"`. EOSE describes one relay response, and an exact-id miss describes this query only. Neither proves global completeness or absence. `truncated: false` means no local output/retention limit was reached. Silent deadlines return partial timed-out successes; all relays failing without a match or EOSE yields `RELAY_UNAVAILABLE`. Explicit cancellation follows SDK request cancellation instead of returning an empty success. Relay statuses preserve EOSE alongside failures or local cancellation. Stop precedence is byte, scan, event, timeout, relay error, EOSE. There are no cursors or exhaustive timeline guarantees.
|
|
45
|
+
|
|
46
|
+
All limits below are startup configuration only; tool arguments may reduce event count and deadline:
|
|
47
|
+
|
|
48
|
+
| Setting | Default | Hard ceiling |
|
|
49
|
+
| --- | ---: | ---: |
|
|
50
|
+
| `maxRelaysPerCall` | 5 | 10 |
|
|
51
|
+
| `limits.events` | 100 | 500 |
|
|
52
|
+
| `limits.timeoutMs` | 5,000 | 30,000 |
|
|
53
|
+
| `maxConcurrentCalls` | 4 | 16 |
|
|
54
|
+
| `signerTimeoutMs` | 5,000 | 300,000 |
|
|
55
|
+
| `limits.responseBytes` | 1 MiB | 4 MiB |
|
|
56
|
+
| `maxInputBytes` | 64 KiB | 256 KiB |
|
|
57
|
+
| `limits.candidates` | 2,000 | 10,000 |
|
|
58
|
+
| `limits.frameBytes` | 256 KiB | 1 MiB |
|
|
59
|
+
| `limits.ingressBytes` | 4 MiB | 16 MiB |
|
|
60
|
+
|
|
61
|
+
Excess concurrency is rejected without queueing. Response accounting includes both output representations and protocol headroom. Candidates count invalid and duplicate events. Frames are size-checked before parsing/verification; Node `ws` also receives `maxPayload`. A WebSocket implementation may allocate the complete message first; application budgets do not bound OS/network buffers or remove synchronous verification cost. Frame/ingress/retained/output exhaustion maps to `byte_limit`, candidate exhaustion to `scan_limit`, and retained count to `event_limit`.
|
|
62
|
+
|
|
63
|
+
Tool errors use safe `INVALID_INPUT`, `POLICY_DENIED`, `RESOURCE_LIMIT`, `RELAY_UNAVAILABLE`, or `INTERNAL_ERROR` messages; protocol schema failures remain SDK protocol errors. Reduce invalid/over-budget requests before retrying; unavailable relays may be retried later. Raw relay errors, configuration secrets, and event content are excluded from diagnostics.
|
|
64
|
+
|
|
65
|
+
Validated 2026-11-17: Node 22.23.2; MCP SDK server/client 2.4.0 over packed stdio. Chromium 159.0.8154.6 and Firefox 159.0 (Playwright 1.65.1) exercised installed core signing, verification, gift-wrap, query, cancellation and subscription cleanup. WebKit and other Node versions remain unverified. The SDK stdio fixture negotiated MCP `2025-11-25` (legacy era). Modern `2026-07-28` negotiation is not claimed. Run `pnpm test:runtime` with the [browser preparation instructions](https://github.com/941design/nostr-events/blob/master/fixtures/runtime/README.md).
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
## Signed publication and identity permissions
|
|
69
|
+
|
|
70
|
+
Publishing is disabled unless `publication: { enabled: true, kinds, authors, relays? }`
|
|
71
|
+
is configured. Kinds and full lowercase author keys are explicit allowlists;
|
|
72
|
+
relay selectors remain configured identifiers. `nostr_publish_event` accepts only
|
|
73
|
+
a complete signed event, optional relay subset and deadline. It rechecks the id
|
|
74
|
+
and signature using a fresh copy before dispatch. It never signs, retries or
|
|
75
|
+
modifies the supplied event. The versioned result preserves its `eventId` and
|
|
76
|
+
per-relay `accepted`, `rejected` or `unknown` statuses plus `dispatched`, `cancelled`
|
|
77
|
+
and `timedOut` and `stopReason` (`complete`, `timeout`, `cancelled`, `byte_limit` or `relay_error`). Budget or relay failures therefore cannot look like ordinary completion. Acceptance is not durable delivery. A cancelled SDK request may
|
|
78
|
+
suppress its response; once a send was attempted, absence of an acknowledgement
|
|
79
|
+
cannot establish that publication did not happen. A deliberate retry must reuse
|
|
80
|
+
the same signed bytes/id.
|
|
81
|
+
|
|
82
|
+
Inject signer authority through the factory's second argument, outside JSON
|
|
83
|
+
configuration and tool arguments. The operator supplies the existing core `Signer`;
|
|
84
|
+
this adapter never stores its private key or selects an identity on a tool call.
|
|
85
|
+
For example, in an application that already owns a signer:
|
|
86
|
+
|
|
87
|
+
```js
|
|
88
|
+
const app = createNostrMcpServer({
|
|
89
|
+
relays: { fixture: 'ws://127.0.0.1:7447' },
|
|
90
|
+
allowLocalRelays: true,
|
|
91
|
+
}, {
|
|
92
|
+
authority: { signer, permissions: { sign: { kinds: [1] } } },
|
|
93
|
+
});
|
|
94
|
+
const signed = await app.execute('nostr_sign_event', {
|
|
95
|
+
template: { kind: 1, created_at: 1, tags: [], content: 'fixture' },
|
|
96
|
+
});
|
|
97
|
+
await app.shutdown(); // The caller still owns signer.
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Permissions are independently granted and snapshotted at construction:
|
|
101
|
+
|
|
102
|
+
| Permission | Enabled operation |
|
|
103
|
+
| --- | --- |
|
|
104
|
+
| `sign: { kinds }` | `nostr_sign_event`; returned signature, author and exact template are checked |
|
|
105
|
+
| `decrypt: { peers }` | `nostr_decrypt`; NIP-44 only, with an explicit peer allowlist |
|
|
106
|
+
| `messaging: { recipients }` | `nostr_send_message`; construct a kind-14 rumor and NIP-59 wrap for an authorized recipient |
|
|
107
|
+
| `inbox: true` | `nostr_read_inbox` and `nostr_unwrap_message`; recipient must be the configured identity |
|
|
108
|
+
| `relayAuth: true` | NIP-42 challenge responses on configured relay connections |
|
|
109
|
+
|
|
110
|
+
Message sending additionally requires publication enabled with kind 1059 allowed.
|
|
111
|
+
Only internally constructed gift-wraps may use their ephemeral outer author in
|
|
112
|
+
this path; externally supplied events still obey the publication author allowlist.
|
|
113
|
+
This is a NIP-59 delivery primitive, not complete NIP-17 messaging: it creates no sender self-copy and uses configured publication relays rather than discovering the recipient's kind-10050 inbox relays. Standard NIP-17 clients may therefore not discover the message. Granting message capability authorizes its internal seal/encryption operations,
|
|
114
|
+
not arbitrary template signing or arbitrary-peer decryption. Private inbox reads
|
|
115
|
+
use a fixed kind-1059/recipient filter; callers cannot choose another identity.
|
|
116
|
+
The core's NIP-59 inner seal verification and outer signature asymmetry are
|
|
117
|
+
preserved for direct unwrap. Public relay reads continue to verify signed events.
|
|
118
|
+
Plaintext is returned only by an authorized operation, never included in logs or
|
|
119
|
+
error messages. Caller approval UI and any data-retention policy remain host duties.
|
|
120
|
+
|
|
121
|
+
Signer work uses the core budget wrapper with bounded concurrency and per-call
|
|
122
|
+
waiting. Signer waits are configurable through trusted `signerTimeoutMs` (default 5 seconds, ceiling 5 minutes), allowing remote approval flows. Read, signer and persistence phases have separate bounded allowances: a relay deadline returns partial read metadata instead of aborting the entire operation. Identity lookup is cached per runtime after its first successful resolution. Inbox processing reuses that identity. Definite malformed wraps count in `invalidMessages`; ambiguous non-timeout remote decrypt failures count separately in `decryptionFailures` and processing continues to later wraps. `decryptionError` and `truncated` preserve the uncertainty about those failed wraps. Explicit cancellation, timeout, or resource exhaustion stops processing while preserving prior messages; `processingTimedOut` identifies the shared processing deadline. The entire inbox decryption phase shares one `signerTimeoutMs` window, so a slow remote signer may return only part of a batch; increase that trusted allowance when needed. Align HTTP/client request deadlines with any longer approval allowance. Cancellation stops adapter-owned
|
|
123
|
+
work; an external signer that ignores cancellation may finish already-dispatched
|
|
124
|
+
work later. It cannot authorize a later adapter step after cancellation. The reused core budget keeps a dispatched, uncooperative signer slot leased until settlement or its lease expiry (30 seconds by default, extended to at least the configured signer wait plus one second); that bounded accounting may outlive the tool wait or factory shutdown.
|
|
125
|
+
|
|
126
|
+
With `relayAuth`, every raw frame is bounded before auth inspection, including
|
|
127
|
+
control frames suppressed during authentication. A conservative per-socket share
|
|
128
|
+
of `limits.ingressBytes / maxRelaysPerCall` bounds the aggregate; a single relay
|
|
129
|
+
may therefore stop below the aggregate ceiling. Collector `metrics.ingressBytes`
|
|
130
|
+
counts delivered frames and excludes suppressed authentication controls. Relay authentication resends a read only after that subscription was explicitly refused with `CLOSED auth-required:`; a challenge on a relay that already serves reads does not duplicate its REQ. If that authentication attempt fails after a refusal is suppressed, the bounded read currently waits for its deadline and reports timeout rather than a separate authentication-failed status. Relay authentication may resume a refused read request, but publication never automatically replays an EVENT after authentication: an authentication rejection remains a reported outcome, and any deliberate retry must reuse the original signed event.
|
|
131
|
+
|
|
132
|
+
## Operator NIP-46 enrollment
|
|
133
|
+
|
|
134
|
+
`enrollNostrConnect(options)` reuses the core connector with a caller-owned
|
|
135
|
+
transport, remote bunker/public-key reference, bridge `clientSecret`, explicit
|
|
136
|
+
trusted relay URLs and permissions. These are operator inputs, never MCP tool
|
|
137
|
+
parameters. Explicit relays override bunker URI hints. The caller must apply its
|
|
138
|
+
relay policy to that transport and trusted list. Enrollment verifies connectivity
|
|
139
|
+
by resolving the signing public key, supports cancellation, and disposes its
|
|
140
|
+
session on failure. Dispose a successful returned session when the operator is
|
|
141
|
+
done; injecting it into a factory does not transfer ownership. The adapter does
|
|
142
|
+
not persist bridge secrets, create approval UI or issue enrollment tokens.
|
|
143
|
+
|
|
144
|
+
## Durable snapshots and live subscriptions
|
|
145
|
+
|
|
146
|
+
Cursor and subscription tools are absent unless their runtime dependencies are
|
|
147
|
+
supplied. Always use a stable, operator-assigned `principalId`, derived from an
|
|
148
|
+
authenticated identity for remote hosting. A session id or tool parameter is not
|
|
149
|
+
an identity. An example for a single local principal:
|
|
150
|
+
|
|
151
|
+
```js
|
|
152
|
+
import { createNostrMcpServer, createFileCursorStore } from '@941design/nostr-mcp';
|
|
153
|
+
const app = createNostrMcpServer(config, {
|
|
154
|
+
principalId: 'local-fixture',
|
|
155
|
+
cursorStore: createFileCursorStore('/absolute/private/cursor-directory'),
|
|
156
|
+
subscriptions: { maxSubscriptions: 4, ttlMs: 30_000 },
|
|
157
|
+
});
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
`nostr_query_page` accepts a filter and page size, performs one bounded relay
|
|
161
|
+
observation, and persists an immutable snapshot before returning its first page.
|
|
162
|
+
`nostr_next_page` reads that retained snapshot using the opaque cursor and page
|
|
163
|
+
size. It does not continue fetching history. Ordering remains descending timestamp
|
|
164
|
+
then ascending id, with `coverage: "unknown"`; relay truncation and dense same-second
|
|
165
|
+
history cannot be repaired by paging the retained set. Cursors bind the principal,
|
|
166
|
+
filter and configured relay destinations, expire, and can be replayed while retained. They may be evicted before their nominal expiry when storage quotas require it. They survive factory/store re-instantiation while retained, using the same persistent
|
|
167
|
+
store and stable principal. A host policy change may invalidate existing cursors.
|
|
168
|
+
|
|
169
|
+
The included file store defaults to 128 entries and 16 MiB total storage, with
|
|
170
|
+
hard ceilings of 1,024 entries and 64 MiB. It uses private directory/file permissions
|
|
171
|
+
and atomic replacement. `maxEntriesPerPrincipal` and `maxBytesPerPrincipal` default to one quarter of the global quotas (at least one entry and 8 KiB). A principal replaces its own oldest snapshots first; new principals can reclaim capacity from the largest owner when the global store is full. Metadata filenames and a bounded in-memory index avoid re-reading every snapshot on each save, and old UUID filenames are migrated once. Recovery reconciles quotas after interrupted writes. `maxPendingOperations` defaults to 4 (ceiling 16), bounding active and queued filesystem operations; a slot stays occupied until physical I/O settles even if its caller stops waiting. Excess operations fail with `RESOURCE_LIMIT` instead of growing an unbounded queue. It supports one process/writer per directory and one shared store instance within that process; use a
|
|
172
|
+
transactional host-provided `CursorStore` for concurrent writers. Atomic replacement can temporarily allocate one extra snapshot; abandoned temporary files are removed on the next read/save under the single-writer contract. Snapshot contents
|
|
173
|
+
include returned events; the operator owns disk encryption, backups, access and
|
|
174
|
+
retention. This is process-restart persistence, not a replicated database or a
|
|
175
|
+
power-loss durability guarantee. Store failures fail the tool without presenting
|
|
176
|
+
a cursor as successfully persisted. Custom stores must enforce their own storage
|
|
177
|
+
bounds; adapter calls also have an operation deadline.
|
|
178
|
+
|
|
179
|
+
`nostr_subscribe` opens genuine live relay subscriptions with a validated filter
|
|
180
|
+
and optional configured relay subset. Its handle stays open after EOSE and is
|
|
181
|
+
owned by this factory/session, independently of the completed creation request.
|
|
182
|
+
`nostr_poll_subscription` drains a bounded batch of observed events;
|
|
183
|
+
`nostr_unsubscribe` closes the handle. The standard MCP resource
|
|
184
|
+
`nostr://subscriptions/{subscriptionId}` supports subscription/update notifications
|
|
185
|
+
and reading observations without draining the queue. Repeated or prefetched resource reads return retained observations; use `nostr_poll_subscription` to consume them. Resource reads enforce the same admission and response limits as tools. Notifications are coalesced per handle until a read or
|
|
186
|
+
poll acknowledges them, rather than accumulating one notification per event.
|
|
187
|
+
Handle possession does not grant access in another principal or session.
|
|
188
|
+
|
|
189
|
+
Live state defaults to four handles with a 30-second lifetime; configured hard
|
|
190
|
+
ceilings are 16 handles and five minutes. Polling does not extend this absolute lifetime. Queue, candidate, ingress and response
|
|
191
|
+
budgets are cumulative for the entire bounded stream window. EOSE records a relay fact and leaves the stream live;
|
|
192
|
+
errors, expiry and limits are explicit. Deduplication lasts for the bounded
|
|
193
|
+
handle lifetime. Once a limit stops a stream, it cannot imply that missed events
|
|
194
|
+
were delivered. Unsubscribe, session termination and shutdown release owned
|
|
195
|
+
sockets/timers/listeners. No live state survives restart; durable snapshots and
|
|
196
|
+
live delivery serve different purposes.
|
|
197
|
+
|
|
198
|
+
## Authenticated HTTP hosting
|
|
199
|
+
|
|
200
|
+
`createNostrMcpHttpHandler(options)` returns `{ handle, shutdown }` for an embedding
|
|
201
|
+
host using the standard Fetch `Request`/`Response` API. It uses the official SDK
|
|
202
|
+
Streamable HTTP transport. It creates no network listener, TLS endpoint, process
|
|
203
|
+
hooks, OAuth authorization server or user accounts. Serve it behind your trusted
|
|
204
|
+
HTTPS infrastructure. The stdio binary remains local stdio.
|
|
205
|
+
|
|
206
|
+
```js
|
|
207
|
+
import { createNostrMcpHttpHandler } from '@941design/nostr-mcp';
|
|
208
|
+
const hosted = createNostrMcpHttpHandler({
|
|
209
|
+
resourceUrl: 'https://nostr.example/mcp',
|
|
210
|
+
authorizationServers: ['https://login.example'],
|
|
211
|
+
verifyToken: token => identityProvider.verifyAccessToken(token),
|
|
212
|
+
createPrincipalApp: (principalId, authInfo) =>
|
|
213
|
+
operatorRegistry.createMcpApp(principalId, authInfo),
|
|
214
|
+
allowedOrigins: ['https://nostr.example'],
|
|
215
|
+
});
|
|
216
|
+
// Your web host forwards validated Request objects to hosted.handle(request).
|
|
217
|
+
// On shutdown, await hosted.shutdown(); your host owns its listener and TLS.
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
`identityProvider` and `operatorRegistry` above are application dependencies, not
|
|
221
|
+
bundled identity services. The verifier must authenticate the actual access token
|
|
222
|
+
using its trusted issuer/signature or introspection, including revocation and
|
|
223
|
+
subject checks. It returns SDK `AuthInfo` containing the token's `clientId`,
|
|
224
|
+
`scopes`, expiry in Unix seconds, resource audience, and
|
|
225
|
+
`extra: { principalId, issuer }`. `principalId` must be a stable verified subject,
|
|
226
|
+
not a client-supplied principal selection or OAuth client id. It must be globally unique across trusted issuers: use an issuer/subject tuple or a verified global account mapping, rather than a bare `sub` that another issuer could reuse. The adapter verifies
|
|
227
|
+
the configured issuer declaration and delegates audience/expiry/required scope
|
|
228
|
+
checks to SDK bearer middleware. Never implement the callback by merely decoding
|
|
229
|
+
an unsigned JWT or accepting arbitrary claims. Tokens are not forwarded to relays.
|
|
230
|
+
|
|
231
|
+
The protected-resource metadata endpoint is
|
|
232
|
+
`/.well-known/oauth-protected-resource` plus the configured resource path. It
|
|
233
|
+
publishes trusted authorization servers and the required `nostr:mcp` access
|
|
234
|
+
scope. Bearer failures include the resource metadata challenge. The host resolves
|
|
235
|
+
any finer scopes to an appropriate principal app and capability policy; possessing
|
|
236
|
+
the base scope does not independently grant signing or private-message authority.
|
|
237
|
+
Create a fresh factory for each session using only that principal's signer,
|
|
238
|
+
permissions and storage context. Use a stable `principalId` in its runtime to
|
|
239
|
+
bind cursors, and share one file-store instance per directory/process if multiple
|
|
240
|
+
session factories use it. The file store's serialization lock is instance-local.
|
|
241
|
+
|
|
242
|
+
Every remote request authenticates, including requests carrying a session id.
|
|
243
|
+
Sessions bind verified principal, issuer, client and scopes. Another principal or
|
|
244
|
+
changed scope set cannot reuse a session; reinitialize instead. Defaults cap the
|
|
245
|
+
host at 64 sessions (ceiling 256), 15-minute idle time (ceiling one hour), and
|
|
246
|
+
64 KiB request bodies (ceiling 256 KiB). Session expiry also respects token expiry.
|
|
247
|
+
The default per-principal cap is eight sessions (bounded by the global cap), and only one SSE GET stream is open per session. `maxConcurrentRequests` defaults to 64 (ceiling 256); `requestTimeoutMs` bounds POST dispatch at 60 seconds by default (ceiling 120 seconds). Host/origin and request-body checks precede tool dispatch, and slow body/token/app
|
|
248
|
+
creation phases have bounded waits. Public hosting requires HTTPS; only explicit
|
|
249
|
+
`allowInsecureLocalhost` permits HTTP on loopback for development. Forward proxy
|
|
250
|
+
headers must be validated by the embedding host; do not construct trusted request
|
|
251
|
+
URLs from arbitrary forwarded headers. Shutdown stops admission and closes
|
|
252
|
+
owned session applications while preserving caller-owned signers.
|
|
253
|
+
|
|
254
|
+
Remote deployment, identity-provider setup and production credentials remain
|
|
255
|
+
operator work. The deterministic test fixtures use local relays and synthetic
|
|
256
|
+
verified token records; they do not establish your issuer or deployment security.
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
Each HTTP POST carries one JSON-RPC message; batch arrays and malformed top-level
|
|
260
|
+
messages are rejected before SDK dispatch. Reusing an active request id returns
|
|
261
|
+
409. Physical dispatch admission is separate from an HTTP caller waiting for its
|
|
262
|
+
response: `maxPendingPosts` defaults to 64 (ceiling 256),
|
|
263
|
+
`maxPendingPostsPerSession` to 4 and `maxPendingPostsPerPrincipal` to 8 (both bounded
|
|
264
|
+
by the global pending limit). This prevents one principal from retaining all
|
|
265
|
+
physical dispatch capacity through fresh sessions or disconnected waiters.
|
|
266
|
+
|
|
267
|
+
A fetch disconnect returns 408 to the abandoned waiter and preserves an existing
|
|
268
|
+
session, its sibling calls and live handles. It does not by itself cancel the
|
|
269
|
+
MCP operation. Physical work remains counted until completion or its bounded
|
|
270
|
+
dispatch deadline. Token verification and app creation also keep their admission
|
|
271
|
+
leases until underlying callbacks settle, including cleanup of a late-created
|
|
272
|
+
orphan app; aborting an HTTP waiter cannot bypass those limits. Host callbacks
|
|
273
|
+
must bound their own external I/O. To cancel an operation, send MCP
|
|
274
|
+
`notifications/cancelled` for
|
|
275
|
+
its request id; this cancels only that operation and releases its transport
|
|
276
|
+
response state. Custom principal applications must settle their own handlers on
|
|
277
|
+
MCP cancellation. An actual dispatch deadline can still retire the affected
|
|
278
|
+
session to clear stalled SDK work; other sessions remain independent. If a write
|
|
279
|
+
was dispatched before transport loss, a missing response cannot prove it was not
|
|
280
|
+
published.
|
|
281
|
+
|
|
282
|
+
Runtime verification remains a manually dispatched CI workflow, following owner
|
|
283
|
+
decision 32 in `specs/owner-decisions-2026-10-29.md` (2026-11-10). It is executable
|
|
284
|
+
local/release evidence, not an automatic pull-request gate.
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { type Filter, type NostrEvent } from "@941design/nostr-events/event";
|
|
2
|
+
import { type ReadLimits, type BoundedReadResult } from "@941design/nostr-events/transport/bounded";
|
|
3
|
+
import type { WebSocketImpl } from "@941design/nostr-events/transport/raw-ws";
|
|
4
|
+
export declare class AdvancedReadError extends Error {
|
|
5
|
+
readonly code: "INVALID_INPUT" | "POLICY_DENIED" | "RESOURCE_LIMIT" | "INTERNAL_ERROR";
|
|
6
|
+
constructor(code: "INVALID_INPUT" | "POLICY_DENIED" | "RESOURCE_LIMIT" | "INTERNAL_ERROR", message: string);
|
|
7
|
+
}
|
|
8
|
+
export interface CursorContext {
|
|
9
|
+
filter: Filter;
|
|
10
|
+
relays: string[];
|
|
11
|
+
}
|
|
12
|
+
export interface CursorSnapshot {
|
|
13
|
+
version: 1;
|
|
14
|
+
principalId: string;
|
|
15
|
+
expiresAt: number;
|
|
16
|
+
context: CursorContext;
|
|
17
|
+
result: BoundedReadResult;
|
|
18
|
+
relayDestinations: Record<string, string>;
|
|
19
|
+
}
|
|
20
|
+
/** A host store must preserve ownership/expiry fields and bound its own storage. */
|
|
21
|
+
export interface CursorStore {
|
|
22
|
+
load(id: string): Promise<unknown>;
|
|
23
|
+
save(id: string, snapshot: CursorSnapshot): Promise<void>;
|
|
24
|
+
}
|
|
25
|
+
/** Single-process, single-writer store. Share one instance per private directory.
|
|
26
|
+
* Filename metadata permits expiry/quota scans without reading event snapshots.
|
|
27
|
+
* Per-principal FIFO eviction and bounded global eviction prevent a full store
|
|
28
|
+
* from denying every subsequent principal until its snapshots expire.
|
|
29
|
+
*/
|
|
30
|
+
export declare function createFileCursorStore(directory: string, options?: {
|
|
31
|
+
maxEntries?: number;
|
|
32
|
+
maxBytes?: number;
|
|
33
|
+
maxEntriesPerPrincipal?: number;
|
|
34
|
+
maxBytesPerPrincipal?: number;
|
|
35
|
+
maxPendingOperations?: number;
|
|
36
|
+
}): CursorStore;
|
|
37
|
+
export interface AdvancedReadOptions {
|
|
38
|
+
principalId: string;
|
|
39
|
+
store?: CursorStore;
|
|
40
|
+
relays: Record<string, string>;
|
|
41
|
+
limits: ReadLimits;
|
|
42
|
+
webSocketImpl: WebSocketImpl;
|
|
43
|
+
maxSubscriptions?: number;
|
|
44
|
+
subscriptionTtlMs?: number;
|
|
45
|
+
cursorTtlMs?: number;
|
|
46
|
+
onUpdate?: (subscriptionId: string) => void;
|
|
47
|
+
}
|
|
48
|
+
export interface LiveResult {
|
|
49
|
+
schemaVersion: "1";
|
|
50
|
+
subscriptionId: string;
|
|
51
|
+
events: NostrEvent[];
|
|
52
|
+
active: boolean;
|
|
53
|
+
coverage: "unknown";
|
|
54
|
+
truncated: boolean;
|
|
55
|
+
stopReason: "live" | "timeout" | "byte_limit" | "scan_limit" | "event_limit" | "relay_error" | "cancelled";
|
|
56
|
+
relays: Record<string, {
|
|
57
|
+
status: "live" | "eose" | "failed" | "cancelled";
|
|
58
|
+
}>;
|
|
59
|
+
metrics: {
|
|
60
|
+
candidates: number;
|
|
61
|
+
ingressBytes: number;
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
export declare function createAdvancedReads(options: AdvancedReadOptions): {
|
|
65
|
+
createPage(result: BoundedReadResult, pageSize: number, context: CursorContext): Promise<{
|
|
66
|
+
events: NostrEvent[];
|
|
67
|
+
provenance: {
|
|
68
|
+
[k: string]: string[];
|
|
69
|
+
};
|
|
70
|
+
query: CursorContext;
|
|
71
|
+
cursor: string | null;
|
|
72
|
+
snapshot: true;
|
|
73
|
+
schemaVersion: "1";
|
|
74
|
+
limits: ReadLimits;
|
|
75
|
+
stopReason: import("@941design/nostr-events/transport/bounded").StopReason;
|
|
76
|
+
timedOut: boolean;
|
|
77
|
+
truncated: boolean;
|
|
78
|
+
coverage: "unknown";
|
|
79
|
+
relays: Record<string, import("@941design/nostr-events/transport/bounded").RelayStatus>;
|
|
80
|
+
metrics: {
|
|
81
|
+
candidates: number;
|
|
82
|
+
ingressBytes: number;
|
|
83
|
+
retainedBytes: number;
|
|
84
|
+
};
|
|
85
|
+
}>;
|
|
86
|
+
nextPage(cursor: string, pageSize: number): Promise<{
|
|
87
|
+
events: NostrEvent[];
|
|
88
|
+
provenance: {
|
|
89
|
+
[k: string]: string[];
|
|
90
|
+
};
|
|
91
|
+
query: CursorContext;
|
|
92
|
+
cursor: string | null;
|
|
93
|
+
snapshot: true;
|
|
94
|
+
schemaVersion: "1";
|
|
95
|
+
limits: ReadLimits;
|
|
96
|
+
stopReason: import("@941design/nostr-events/transport/bounded").StopReason;
|
|
97
|
+
timedOut: boolean;
|
|
98
|
+
truncated: boolean;
|
|
99
|
+
coverage: "unknown";
|
|
100
|
+
relays: Record<string, import("@941design/nostr-events/transport/bounded").RelayStatus>;
|
|
101
|
+
metrics: {
|
|
102
|
+
candidates: number;
|
|
103
|
+
ingressBytes: number;
|
|
104
|
+
retainedBytes: number;
|
|
105
|
+
};
|
|
106
|
+
}>;
|
|
107
|
+
subscribe(input: {
|
|
108
|
+
filter: Filter;
|
|
109
|
+
relays?: string[];
|
|
110
|
+
signal?: AbortSignal;
|
|
111
|
+
}): {
|
|
112
|
+
schemaVersion: "1";
|
|
113
|
+
subscriptionId: `${string}-${string}-${string}-${string}-${string}`;
|
|
114
|
+
coverage: "unknown";
|
|
115
|
+
delivery: "poll";
|
|
116
|
+
};
|
|
117
|
+
peek(input: {
|
|
118
|
+
subscriptionId: string;
|
|
119
|
+
limit?: number;
|
|
120
|
+
}): {
|
|
121
|
+
events: NostrEvent[];
|
|
122
|
+
schemaVersion: "1";
|
|
123
|
+
subscriptionId: string;
|
|
124
|
+
active: boolean;
|
|
125
|
+
coverage: "unknown";
|
|
126
|
+
truncated: boolean;
|
|
127
|
+
stopReason: "live" | "timeout" | "byte_limit" | "scan_limit" | "event_limit" | "relay_error" | "cancelled";
|
|
128
|
+
relays: Record<string, {
|
|
129
|
+
status: "live" | "eose" | "failed" | "cancelled";
|
|
130
|
+
}>;
|
|
131
|
+
metrics: {
|
|
132
|
+
candidates: number;
|
|
133
|
+
ingressBytes: number;
|
|
134
|
+
};
|
|
135
|
+
};
|
|
136
|
+
poll(input: {
|
|
137
|
+
subscriptionId: string;
|
|
138
|
+
limit?: number;
|
|
139
|
+
}): {
|
|
140
|
+
events: NostrEvent[];
|
|
141
|
+
schemaVersion: "1";
|
|
142
|
+
subscriptionId: string;
|
|
143
|
+
active: boolean;
|
|
144
|
+
coverage: "unknown";
|
|
145
|
+
truncated: boolean;
|
|
146
|
+
stopReason: "live" | "timeout" | "byte_limit" | "scan_limit" | "event_limit" | "relay_error" | "cancelled";
|
|
147
|
+
relays: Record<string, {
|
|
148
|
+
status: "live" | "eose" | "failed" | "cancelled";
|
|
149
|
+
}>;
|
|
150
|
+
metrics: {
|
|
151
|
+
candidates: number;
|
|
152
|
+
ingressBytes: number;
|
|
153
|
+
};
|
|
154
|
+
};
|
|
155
|
+
ownsSubscription(id: string): boolean;
|
|
156
|
+
unsubscribe(id: string): {
|
|
157
|
+
closed: true;
|
|
158
|
+
};
|
|
159
|
+
shutdown(): void;
|
|
160
|
+
};
|