Skip to content

Commit cac66b8

Browse files
Add type guard for DurableObjectNamespace (#295)
* Add type guard for DurableObjectNamespace Introduced a type guard function `isDurableObjectNamespace` to validate objects as DurableObjectNamespace. Updated relevant checks in McpAgent to use this type guard for improved type safety and clarity. Fixes #294 * Update index.ts
1 parent 9c460fb commit cac66b8

File tree

2 files changed

+26
-6
lines changed

2 files changed

+26
-6
lines changed

.changeset/modern-crabs-smash.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"agents": patch
3+
---
4+
5+
duck typing DurableObjectNamespace type

packages/agents/src/mcp/index.ts

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,19 @@ function corsHeaders(request: Request, corsOptions: CORSOptions = {}) {
3030
};
3131
}
3232

33+
function isDurableObjectNamespace(
34+
namespace: unknown
35+
): namespace is DurableObjectNamespace<McpAgent> {
36+
return (
37+
typeof namespace === "object" &&
38+
namespace !== null &&
39+
"newUniqueId" in namespace &&
40+
typeof namespace.newUniqueId === "function" &&
41+
"idFromName" in namespace &&
42+
typeof namespace.idFromName === "function"
43+
);
44+
}
45+
3346
function handleCORS(
3447
request: Request,
3548
corsOptions?: CORSOptions
@@ -557,12 +570,13 @@ export abstract class McpAgent<
557570
return new Response("Invalid binding", { status: 500 });
558571
}
559572

560-
// Ensure that the biding is to a DurableObject
561-
if (bindingValue.toString() !== "[object DurableObjectNamespace]") {
573+
// Ensure that the binding is to a DurableObject
574+
if (!isDurableObjectNamespace(bindingValue)) {
562575
return new Response("Invalid binding", { status: 500 });
563576
}
564577

565-
const namespace = bindingValue as DurableObjectNamespace<McpAgent>;
578+
const namespace =
579+
bindingValue satisfies DurableObjectNamespace<McpAgent>;
566580

567581
// Handle initial SSE connection
568582
if (request.method === "GET" && basePattern.test(url)) {
@@ -785,12 +799,13 @@ export abstract class McpAgent<
785799
return new Response("Invalid binding", { status: 500 });
786800
}
787801

788-
// Ensure that the biding is to a DurableObject
789-
if (bindingValue.toString() !== "[object DurableObjectNamespace]") {
802+
// Ensure that the binding is to a DurableObject
803+
if (!isDurableObjectNamespace(bindingValue)) {
790804
return new Response("Invalid binding", { status: 500 });
791805
}
792806

793-
const namespace = bindingValue as DurableObjectNamespace<McpAgent>;
807+
const namespace =
808+
bindingValue satisfies DurableObjectNamespace<McpAgent>;
794809

795810
if (request.method === "POST" && basePattern.test(url)) {
796811
// validate the Accept header

0 commit comments

Comments
 (0)