@panyam/servicekit-client 0.0.6 → 0.0.7

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.
@@ -0,0 +1,171 @@
1
+ /**
2
+ * StreamableClient — Client for ServiceKit StreamableServe endpoints.
3
+ *
4
+ * Supports the "POST-that-optionally-streams" pattern from MCP 2025-03-26:
5
+ * a single endpoint returns either a JSON response (application/json) or
6
+ * an SSE event stream (text/event-stream) based on the server's decision.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * const rpc = new StreamableClient<MyRequest, MyResponse>();
11
+ *
12
+ * // Single response (server returns application/json)
13
+ * const result = await rpc.post('http://localhost:8080/rpc', { method: 'getUser' });
14
+ * console.log(result); // MyResponse
15
+ *
16
+ * // Streaming response (server returns text/event-stream)
17
+ * rpc.onEvent = (type, data) => console.log('progress:', data);
18
+ * rpc.onDone = () => console.log('done');
19
+ * await rpc.post('http://localhost:8080/rpc', { method: 'longOp' });
20
+ * ```
21
+ */
22
+
23
+ import type { MessageHandler, ErrorHandler, VoidHandler } from './types';
24
+ import { createParser } from './sse-parser';
25
+
26
+ /**
27
+ * Options for configuring StreamableClient.
28
+ */
29
+ export interface StreamableClientOptions {
30
+ /**
31
+ * Custom fetch implementation (for Node.js or testing).
32
+ * Default: globalThis.fetch
33
+ */
34
+ fetch?: typeof globalThis.fetch;
35
+
36
+ /**
37
+ * HTTP headers to include in requests.
38
+ * Useful for authentication tokens.
39
+ */
40
+ headers?: Record<string, string>;
41
+ }
42
+
43
+ /**
44
+ * Client for StreamableServe endpoints that support both synchronous JSON
45
+ * responses and SSE event streaming from a single POST endpoint.
46
+ *
47
+ * The client POSTs a JSON request body and detects the response Content-Type:
48
+ * - `application/json` → parses body, returns as TOut
49
+ * - `text/event-stream` → streams events via onMessage/onEvent callbacks,
50
+ * calls onDone when complete, returns undefined
51
+ *
52
+ * @see https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http
53
+ */
54
+ export class StreamableClient<TReq = unknown, TOut = unknown> {
55
+ private _fetch: typeof globalThis.fetch;
56
+ private _headers: Record<string, string>;
57
+ private _abortController: AbortController | null = null;
58
+
59
+ /** Called when an unnamed data event is received during streaming. */
60
+ public onMessage: MessageHandler<TOut> = () => {};
61
+
62
+ /** Called when a named event is received during streaming. */
63
+ public onEvent: (event: string, data: TOut) => void = () => {};
64
+
65
+ /** Called when the SSE stream completes (channel closed by server). */
66
+ public onDone: VoidHandler = () => {};
67
+
68
+ /** Called when an error occurs. */
69
+ public onError: ErrorHandler = () => {};
70
+
71
+ constructor(options: StreamableClientOptions = {}) {
72
+ this._fetch = options.fetch ?? globalThis.fetch;
73
+ this._headers = options.headers ?? {};
74
+ }
75
+
76
+ /**
77
+ * POST a request to a StreamableServe endpoint.
78
+ *
79
+ * Returns the parsed response for JSON responses, or undefined for
80
+ * streaming responses (events dispatched via callbacks).
81
+ *
82
+ * @param url The endpoint URL
83
+ * @param body The request body (JSON-serialized)
84
+ * @returns Parsed response (JSON path) or undefined (streaming path)
85
+ */
86
+ async post(url: string, body: TReq): Promise<TOut | undefined> {
87
+ this._abortController = new AbortController();
88
+
89
+ const response = await this._fetch(url, {
90
+ method: 'POST',
91
+ headers: {
92
+ 'Content-Type': 'application/json',
93
+ Accept: 'text/event-stream, application/json',
94
+ ...this._headers,
95
+ },
96
+ body: JSON.stringify(body),
97
+ signal: this._abortController.signal,
98
+ });
99
+
100
+ if (!response.ok) {
101
+ throw new Error(`Request failed: HTTP ${response.status}`);
102
+ }
103
+
104
+ const contentType = response.headers.get('Content-Type') ?? '';
105
+
106
+ // JSON response path (synchronous)
107
+ if (contentType.includes('application/json')) {
108
+ const result = (await response.json()) as TOut;
109
+ return result;
110
+ }
111
+
112
+ // SSE streaming path
113
+ if (contentType.includes('text/event-stream')) {
114
+ if (!response.body) {
115
+ throw new Error('Streaming response has no body');
116
+ }
117
+ await this._readStream(response.body);
118
+ return undefined;
119
+ }
120
+
121
+ throw new Error(`Unexpected Content-Type: ${contentType}`);
122
+ }
123
+
124
+ /**
125
+ * Abort the current request/stream.
126
+ */
127
+ close(): void {
128
+ if (this._abortController) {
129
+ this._abortController.abort();
130
+ this._abortController = null;
131
+ }
132
+ }
133
+
134
+ /** Read an SSE stream and dispatch events. */
135
+ private async _readStream(body: ReadableStream<Uint8Array>): Promise<void> {
136
+ const reader = body.getReader();
137
+ const decoder = new TextDecoder();
138
+
139
+ const parser = createParser({
140
+ onEvent: (event) => {
141
+ let parsed: TOut;
142
+ try {
143
+ parsed = JSON.parse(event.data) as TOut;
144
+ } catch {
145
+ parsed = event.data as unknown as TOut;
146
+ }
147
+
148
+ if (event.event) {
149
+ this.onEvent(event.event, parsed);
150
+ } else {
151
+ this.onMessage(parsed);
152
+ }
153
+ },
154
+ });
155
+
156
+ try {
157
+ while (true) {
158
+ const { done, value } = await reader.read();
159
+ if (done) break;
160
+ parser.feed(decoder.decode(value, { stream: true }));
161
+ }
162
+ } catch (err) {
163
+ if (err instanceof Error && err.name === 'AbortError') {
164
+ return;
165
+ }
166
+ this.onError(String(err));
167
+ } finally {
168
+ this.onDone();
169
+ }
170
+ }
171
+ }