Open History to see the last commit
1diff --git a/dist/unstable/ai/McpServer.js b/dist/unstable/ai/McpServer.js
2index 755e41c..dc431aa 100644
3--- a/dist/unstable/ai/McpServer.js
4+++ b/dist/unstable/ai/McpServer.js
5@@ -262,6 +262,26 @@ const runWithProtocolState = /*#__PURE__*/Effect.fnUntraced(function* (options,
6 const server = yield* McpServer;
7 const isHttp = Option.isSome(yield* Effect.serviceOption(HttpRouter.HttpRouter));
8 const sessions = protocolState.sessions;
9+ if (isHttp && options.path !== undefined) {
10+ const router = yield* HttpRouter.HttpRouter;
11+ yield* router.add("DELETE", options.path, Effect.gen(function* () {
12+ const request = yield* HttpServerRequest.HttpServerRequest;
13+ const sessionId = request.headers[MCP_SESSION_ID_HEADER];
14+ if (sessionId === undefined) {
15+ return HttpServerResponse.empty({
16+ status: 400
17+ });
18+ }
19+ if (!sessions.bySessionId.delete(sessionId)) {
20+ return HttpServerResponse.empty({
21+ status: 404
22+ });
23+ }
24+ return HttpServerResponse.empty({
25+ status: 204
26+ });
27+ }));
28+ }
29 const clientProtocols = new Map();
30 const cancelledRequests = new Map();
31 const handlers = yield* Layer.build(layerHandlers(options, {
32@@ -719,7 +739,7 @@ export const layerHttp = options => {
33 const methodNotAllowed = request => Effect.succeed(request.headers.origin !== undefined && !options.allowedOrigins?.includes(request.headers.origin) ? HttpServerResponse.empty({
34 status: 403
35 }) : methodNotAllowedResponse);
36- const routes = Layer.mergeAll(HttpRouter.add("GET", options.path, methodNotAllowed), HttpRouter.add("PUT", options.path, methodNotAllowed), HttpRouter.add("PATCH", options.path, methodNotAllowed), HttpRouter.add("DELETE", options.path, methodNotAllowed), HttpRouter.add("OPTIONS", options.path, methodNotAllowed));
37+ const routes = Layer.mergeAll(HttpRouter.add("GET", options.path, methodNotAllowed), HttpRouter.add("PUT", options.path, methodNotAllowed), HttpRouter.add("PATCH", options.path, methodNotAllowed), HttpRouter.add("OPTIONS", options.path, methodNotAllowed));
38 return Layer.merge(layerWithProtocolState(options), routes).pipe(Layer.provide(layerMcpProtocolHttp(options)), Layer.provide(protocolState), Layer.provide(RpcSerialization.layerJsonRpc()));
39 };
40 const layerMcpProtocolHttp = options => Layer.effect(RpcServer.Protocol)(Effect.gen(function* () {
41diff --git a/dist/unstable/rpc/RpcClient.d.ts b/dist/unstable/rpc/RpcClient.d.ts
42index aba2779..581d267 100644
43--- a/dist/unstable/rpc/RpcClient.d.ts
44+++ b/dist/unstable/rpc/RpcClient.d.ts
45@@ -2,6 +2,7 @@ import * as Cause from "../../Cause.ts";
46 import * as Context from "../../Context.ts";
47 import type * as Duration from "../../Duration.ts";
48 import * as Effect from "../../Effect.ts";
49+import * as Exit from "../../Exit.ts";
50 import * as Layer from "../../Layer.ts";
51 import * as Queue from "../../Queue.ts";
52 import * as Schedule from "../../Schedule.ts";
53@@ -261,9 +262,40 @@ export declare const layerProtocolWorker: (options: {
54 readonly targetUtilization?: number | undefined;
55 readonly timeToLive: Duration.Input;
56 }) => Layer.Layer<Protocol, WorkerError, Worker.WorkerPlatform | Worker.Spawner>;
57+declare const RequestHooks_base: Context.ServiceClass<RequestHooks, "effect/rpc/RpcClient/RequestHooks", {
58+ readonly onRequestStart?: ((info: {
59+ readonly id: RequestId;
60+ readonly tag: string;
61+ readonly stream: boolean;
62+ }) => Effect.Effect<void>) | undefined;
63+ readonly onRequestChunk?: ((info: {
64+ readonly id: RequestId;
65+ readonly tag: string;
66+ readonly chunkCount: number;
67+ }) => Effect.Effect<void>) | undefined;
68+ readonly onRequestExit?: ((info: {
69+ readonly id: RequestId;
70+ readonly tag: string;
71+ readonly stream: boolean;
72+ readonly exit: Exit.Exit<unknown, unknown>;
73+ }) => Effect.Effect<void>) | undefined;
74+ readonly onRequestInterrupt?: ((info: {
75+ readonly id: RequestId;
76+ readonly tag?: string | undefined;
77+ }) => Effect.Effect<void>) | undefined;
78+}>;
79+/**
80+ * @since 4.0.0
81+ * @category RequestHooks
82+ */
83+export declare class RequestHooks extends RequestHooks_base {
84+}
85 declare const ConnectionHooks_base: Context.ServiceClass<ConnectionHooks, "effect/rpc/RpcClient/ConnectionHooks", {
86 readonly onConnect: Effect.Effect<void>;
87 readonly onDisconnect: Effect.Effect<void>;
88+ readonly onPing?: Effect.Effect<void> | undefined;
89+ readonly onPong?: Effect.Effect<void> | undefined;
90+ readonly onPingTimeout?: Effect.Effect<void> | undefined;
91 }>;
92 /**
93 * Represents optional client protocol hooks that run when a transport connects
94diff --git a/dist/unstable/rpc/RpcClient.js b/dist/unstable/rpc/RpcClient.js
95index b536d0a..12ffac0 100644
96--- a/dist/unstable/rpc/RpcClient.js
97+++ b/dist/unstable/rpc/RpcClient.js
98@@ -47,6 +47,7 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
99 const services = yield* Effect.context();
100 const scope = Context.get(services, Scope.Scope);
101 const entries = new Map();
102+ const hooks = yield* Effect.serviceOption(RequestHooks);
103 let isShutdown = false;
104 yield* Scope.addFinalizer(scope, Effect.withFiber(parent => {
105 isShutdown = true;
106@@ -84,6 +85,11 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
107 return Effect.interrupt;
108 }
109 const id = generateRequestId();
110+ const onStart = Option.isSome(hooks) && hooks.value.onRequestStart ? hooks.value.onRequestStart({
111+ id,
112+ tag: rpc._tag,
113+ stream: false
114+ }) : Effect.void;
115 const send = middleware(message => options.onFromClient({
116 message,
117 context,
118@@ -101,7 +107,7 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
119 headers: Headers.merge(parentFiber.getRef(CurrentHeaders), headers)
120 });
121 if (discard) {
122- return send;
123+ return onStart.pipe(Effect.andThen(send));
124 }
125 let fiber;
126 return Effect.onInterrupt(Effect.callback(resume => {
127@@ -119,7 +125,7 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
128 }
129 };
130 entries.set(id, entry);
131- fiber = send.pipe(span ? Effect.withParentSpan(span, {
132+ fiber = onStart.pipe(Effect.andThen(send), span ? Effect.withParentSpan(span, {
133 captureStackTrace: false
134 }) : identity, Effect.runForkWith(parentFiber.context));
135 fiber.addObserver(exit => {
136@@ -128,8 +134,9 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
137 }
138 });
139 }), interruptors => {
140+ const entry = entries.get(id);
141 entries.delete(id);
142- return Effect.andThen(Fiber.interrupt(fiber), sendInterrupt(id, Array.from(interruptors), context));
143+ return Effect.andThen(Fiber.interrupt(fiber), sendInterrupt(id, Array.from(interruptors), context, entry?.rpc._tag));
144 });
145 });
146 const onStreamRequest = Effect.fnUntraced(function* (rpc, middleware, payload, headers, streamBufferSize, context) {
147@@ -141,11 +148,17 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
148 });
149 const fiber = Fiber.getCurrent();
150 const id = generateRequestId();
151+ const onStart = Option.isSome(hooks) && hooks.value.onRequestStart ? hooks.value.onRequestStart({
152+ id,
153+ tag: rpc._tag,
154+ stream: true
155+ }) : Effect.void;
156 const scope = Context.getUnsafe(fiber.context, Scope.Scope);
157 yield* Scope.addFinalizerExit(scope, exit => {
158- if (!entries.has(id)) return Effect.void;
159+ const entry = entries.get(id);
160+ if (!entry) return Effect.void;
161 entries.delete(id);
162- return sendInterrupt(id, Exit.isFailure(exit) ? Array.from(Cause.interruptors(exit.cause)) : [], context);
163+ return sendInterrupt(id, Exit.isFailure(exit) ? Array.from(Cause.interruptors(exit.cause)) : [], context, entry.rpc._tag);
164 });
165 const queue = yield* Queue.bounded(streamBufferSize);
166 entries.set(id, {
167@@ -153,9 +166,10 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
168 rpc,
169 queue,
170 scope,
171- context
172+ context,
173+ chunkCount: 0
174 });
175- yield* middleware(message => options.onFromClient({
176+ yield* onStart.pipe(Effect.andThen(middleware(message => options.onFromClient({
177 message,
178 context,
179 discard: false
180@@ -170,7 +184,7 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
181 sampled: span.sampled
182 } : {}),
183 headers: Headers.merge(fiber.getRef(CurrentHeaders), headers)
184- }).pipe(span ? Effect.withParentSpan(span, {
185+ }))).pipe(span ? Effect.withParentSpan(span, {
186 captureStackTrace: false
187 }) : identity, Effect.catchCause(error => Queue.failCause(queue, error)), Effect.interruptible, Effect.forkIn(scope, {
188 startImmediately: true
189@@ -200,7 +214,10 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
190 });
191 };
192 };
193- const sendInterrupt = (requestId, interruptors, context) => Effect.callback(resume => {
194+ const sendInterrupt = (requestId, interruptors, context, tag) => (Option.isSome(hooks) && hooks.value.onRequestInterrupt ? hooks.value.onRequestInterrupt({
195+ id: requestId,
196+ tag
197+ }) : Effect.void).pipe(Effect.andThen(Effect.callback(resume => {
198 const parentFiber = Fiber.getCurrent();
199 const fiber = options.onFromClient({
200 message: {
201@@ -214,7 +231,7 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
202 fiber.addObserver(() => {
203 resume(Effect.void);
204 });
205- });
206+ })));
207 const write = message => {
208 switch (message._tag) {
209 case "Chunk":
210@@ -222,7 +239,13 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
211 const requestId = message.requestId;
212 const entry = entries.get(requestId);
213 if (!entry || entry._tag !== "Queue") return Effect.void;
214- return Queue.offerAll(entry.queue, message.values).pipe(supportsAck ? Effect.flatMap(() => options.onFromClient({
215+ const chunkCount = entry.chunkCount += message.values.length;
216+ const onChunk = Option.isSome(hooks) && hooks.value.onRequestChunk ? hooks.value.onRequestChunk({
217+ id: requestId,
218+ tag: entry.rpc._tag,
219+ chunkCount
220+ }) : Effect.void;
221+ return Queue.offerAll(entry.queue, message.values).pipe(Effect.andThen(onChunk), supportsAck ? Effect.flatMap(() => options.onFromClient({
222 message: {
223 _tag: "Ack",
224 requestId: message.requestId
225@@ -237,11 +260,18 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
226 const entry = entries.get(requestId);
227 if (!entry) return Effect.void;
228 entries.delete(requestId);
229+ const onExit = Option.isSome(hooks) && hooks.value.onRequestExit ? hooks.value.onRequestExit({
230+ id: requestId,
231+ tag: entry.rpc._tag,
232+ stream: entry._tag === "Queue",
233+ exit: message.exit
234+ }) : Effect.void;
235 if (entry._tag === "Effect") {
236- entry.resume(message.exit);
237- return Effect.void;
238+ return onExit.pipe(Effect.andThen(Effect.sync(() => {
239+ entry.resume(message.exit);
240+ })));
241 }
242- return message.exit._tag === "Success" ? Queue.end(entry.queue) : Queue.failCause(entry.queue, message.exit.cause);
243+ return onExit.pipe(Effect.andThen(message.exit._tag === "Success" ? Queue.end(entry.queue) : Queue.failCause(entry.queue, message.exit.cause)));
244 }
245 case "Defect":
246 {
247@@ -590,7 +620,7 @@ export const makeProtocolSocket = options => Protocol.make(Effect.fnUntraced(fun
248 const requestClientMap = new Map();
249 const write = yield* socket.writer;
250 let parser = serialization.makeUnsafe();
251- const pinger = yield* makePinger(write(parser.encode(constPing)));
252+ const pinger = yield* makePinger(write(parser.encode(constPing)), Option.isSome(hooks) ? hooks.value : undefined);
253 let currentError;
254 const onOpen = Effect.suspend(() => {
255 currentError = undefined;
256@@ -610,8 +640,7 @@ export const makeProtocolSocket = options => Protocol.make(Effect.fnUntraced(fun
257 body: () => {
258 const response = responses[i++];
259 if (response._tag === "Pong") {
260- pinger.onPong();
261- return Effect.void;
262+ return pinger.onPong;
263 }
264 if (Object.hasOwn(response, "requestId")) {
265 const requestId = response.requestId;
266@@ -640,12 +669,12 @@ export const makeProtocolSocket = options => Protocol.make(Effect.fnUntraced(fun
267 }
268 }, {
269 onOpen
270- }).pipe(Effect.raceFirst(Effect.flatMap(pinger.timeout, () => Effect.fail(new Socket.SocketError({
271+ }).pipe(Effect.raceFirst(Effect.flatMap(pinger.timeout, () => (Option.isSome(hooks) && hooks.value.onPingTimeout ? hooks.value.onPingTimeout : Effect.void).pipe(Effect.andThen(Effect.fail(new Socket.SocketError({
272 reason: new Socket.SocketOpenError({
273 kind: "Timeout",
274 cause: new Error("ping timeout")
275 })
276- })))));
277+ })))))));
278 }).pipe(Effect.flatMap(() => Effect.fail(new Socket.SocketError({
279 reason: new Socket.SocketCloseError({
280 code: 1000
281@@ -687,20 +716,28 @@ export const makeProtocolSocket = options => Protocol.make(Effect.fnUntraced(fun
282 };
283 }));
284 const defaultRetryPolicy = /*#__PURE__*/Schedule.min([/*#__PURE__*/Schedule.exponential(500, 1.5), /*#__PURE__*/Schedule.spaced(5000)]);
285-const makePinger = /*#__PURE__*/Effect.fnUntraced(function* (writePing) {
286+const makePinger = /*#__PURE__*/Effect.fnUntraced(function* (writePing, hooks) {
287 let recievedPong = true;
288+ let missedPongs = 0;
289 const latch = Latch.makeUnsafe();
290 const reset = () => {
291 recievedPong = true;
292+ missedPongs = 0;
293 latch.closeUnsafe();
294 };
295- const onPong = () => {
296- recievedPong = true;
297- };
298+ const onPong = Effect.sync(() => {
299+ recievedPong = true;
300+ missedPongs = 0;
301+ }).pipe(Effect.andThen(hooks?.onPong ?? Effect.void));
302 yield* Effect.suspend(() => {
303- if (!recievedPong) return latch.open;
304- recievedPong = false;
305- return writePing;
306+ if (!recievedPong) {
307+ missedPongs += 1;
308+ if (missedPongs >= 3) return latch.open;
309+ return (hooks?.onPing ?? Effect.void).pipe(Effect.andThen(writePing));
310+ }
311+ recievedPong = false;
312+ missedPongs = 0;
313+ return (hooks?.onPing ?? Effect.void).pipe(Effect.andThen(writePing));
314 }).pipe(Effect.delay("5 seconds"), Effect.ignore, Effect.forever, Effect.interruptible, Effect.forkScoped);
315 return {
316 timeout: latch.await,
317@@ -843,6 +880,11 @@ export const makeProtocolWorker = options => Protocol.make(Effect.fnUntraced(fun
318 * @since 4.0.0
319 */
320 export const layerProtocolWorker = /*#__PURE__*/flow(makeProtocolWorker, /*#__PURE__*/Layer.effect(Protocol));
321+/**
322+ * @since 4.0.0
323+ * @category RequestHooks
324+ */
325+export class RequestHooks extends /*#__PURE__*/Context.Service()("effect/rpc/RpcClient/RequestHooks") {}
326 /**
327 * Represents optional client protocol hooks that run when a transport connects
328 * and disconnects.