Open History to see the last commit
1diff --git a/dist/unstable/ai/McpServer.js b/dist/unstable/ai/McpServer.js
2index ce9dda4..95c38f2 100644
3--- a/dist/unstable/ai/McpServer.js
4+++ b/dist/unstable/ai/McpServer.js
5@@ -444,6 +444,26 @@ const runWithProtocolState = /*#__PURE__*/Effect.fnUntraced(function* (options,
6 const defaultLogLevel = yield* CurrentLogLevel;
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 activeRequests = new Map();
31 const clientProfiles = new Map();
32@@ -942,7 +962,7 @@ export const layerHttp = options => {
33 const methodNotAllowed = request => isAllowedMcpOrigin(request, options.allowedOrigins) ? Effect.succeed(methodNotAllowedResponse) : Effect.succeed(HttpServerResponse.empty({
34 status: 403
35 }));
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 1a471aa..7233784 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@@ -280,9 +281,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 ec78917..342f9d7 100644
96--- a/dist/unstable/rpc/RpcClient.js
97+++ b/dist/unstable/rpc/RpcClient.js
98@@ -49,6 +49,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@@ -86,6 +87,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@@ -103,7 +109,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@@ -121,7 +127,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@@ -130,8 +136,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@@ -143,11 +150,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@@ -155,9 +168,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@@ -172,7 +186,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@@ -202,7 +216,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@@ -216,7 +233,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@@ -224,7 +241,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@@ -239,11 +262,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@@ -603,7 +633,7 @@ export const makeProtocolSocket = options => Protocol.make(Effect.fnUntraced(fun
248 // `parser` is replaced on every connect, and a stateful serialization
249 // encodes against the connection it is writing to, so the ping is encoded
250 // when it is sent rather than once up front.
251- const pinger = yield* makePinger(Effect.suspend(() => write(parser.encode(constPing))));
252+ const pinger = yield* makePinger(Effect.suspend(() => write(parser.encode(constPing))), Option.isSome(hooks) ? hooks.value : undefined);
253 let currentError;
254 const onOpen = Effect.suspend(() => {
255 currentError = undefined;
256@@ -630,8 +660,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@@ -660,12 +689,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@@ -710,20 +739,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+ const onPong = Effect.sync(() => {
297 recievedPong = true;
298- };
299+ missedPongs = 0;
300+ }).pipe(Effect.andThen(hooks?.onPong ?? Effect.void));
301 yield* Effect.suspend(() => {
302- if (!recievedPong) return latch.open;
303+ if (!recievedPong) {
304+ missedPongs += 1;
305+ if (missedPongs >= 3) return latch.open;
306+ return (hooks?.onPing ?? Effect.void).pipe(Effect.andThen(writePing));
307+ }
308 recievedPong = false;
309- return writePing;
310+ missedPongs = 0;
311+ return (hooks?.onPing ?? Effect.void).pipe(Effect.andThen(writePing));
312 }).pipe(Effect.delay("5 seconds"), Effect.ignore, Effect.forever, Effect.interruptible, Effect.forkScoped);
313 return {
314 timeout: latch.await,
315@@ -874,6 +911,11 @@ export const makeProtocolWorker = options => Protocol.make(Effect.fnUntraced(fun
316 * @since 4.0.0
317 */
318 export const layerProtocolWorker = /*#__PURE__*/flow(makeProtocolWorker, /*#__PURE__*/Layer.effect(Protocol));
319+/**
320+ * @since 4.0.0
321+ * @category RequestHooks
322+ */
323+export class RequestHooks extends /*#__PURE__*/Context.Service()("effect/rpc/RpcClient/RequestHooks") {}
324 /**
325 * Represents optional client protocol hooks that run when a transport connects
326 * and disconnects.