-
Notifications
You must be signed in to change notification settings - Fork 22
fix: use ejson parsing for stdio messages #218
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
import { JSONRPCMessage, JSONRPCMessageSchema } from "@modelcontextprotocol/sdk/types.js"; | ||
import { EJSON } from "bson"; | ||
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; | ||
|
||
// This is almost a copy of ReadBuffer from @modelcontextprotocol/sdk | ||
// but it uses EJSON.parse instead of JSON.parse to handle BSON types | ||
export class EJsonReadBuffer { | ||
private _buffer?: Buffer; | ||
|
||
append(chunk: Buffer): void { | ||
this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; | ||
} | ||
|
||
readMessage(): JSONRPCMessage | null { | ||
if (!this._buffer) { | ||
return null; | ||
} | ||
|
||
const index = this._buffer.indexOf("\n"); | ||
if (index === -1) { | ||
return null; | ||
} | ||
|
||
const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, ""); | ||
this._buffer = this._buffer.subarray(index + 1); | ||
|
||
// This is using EJSON.parse instead of JSON.parse to handle BSON types | ||
return JSONRPCMessageSchema.parse(EJSON.parse(line)); | ||
} | ||
|
||
clear(): void { | ||
this._buffer = undefined; | ||
} | ||
} | ||
|
||
// This is a hacky workaround for https://github.com/mongodb-js/mongodb-mcp-server/issues/211 | ||
// The underlying issue is that StdioServerTransport uses JSON.parse to deserialize | ||
// messages, but that doesn't handle bson types, such as ObjectId when serialized as EJSON. | ||
// | ||
// This function creates a StdioServerTransport and replaces the internal readBuffer with EJsonReadBuffer | ||
// that uses EJson.parse instead. | ||
export function createEJsonTransport(): StdioServerTransport { | ||
const server = new StdioServerTransport(); | ||
server["_readBuffer"] = new EJsonReadBuffer(); | ||
|
||
return server; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
import { Decimal128, MaxKey, MinKey, ObjectId, Timestamp, UUID } from "bson"; | ||
import { createEJsonTransport, EJsonReadBuffer } from "../../src/helpers/EJsonTransport.js"; | ||
import { JSONRPCMessage } from "@modelcontextprotocol/sdk/types.js"; | ||
import { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types.js"; | ||
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; | ||
import { Readable } from "stream"; | ||
import { ReadBuffer } from "@modelcontextprotocol/sdk/shared/stdio.js"; | ||
|
||
describe("EJsonTransport", () => { | ||
let transport: StdioServerTransport; | ||
beforeEach(async () => { | ||
transport = createEJsonTransport(); | ||
await transport.start(); | ||
}); | ||
|
||
afterEach(async () => { | ||
await transport.close(); | ||
}); | ||
|
||
it("ejson deserializes messages", () => { | ||
const messages: { message: JSONRPCMessage; extra?: { authInfo?: AuthInfo } }[] = []; | ||
transport.onmessage = ( | ||
message, | ||
extra?: { | ||
authInfo?: AuthInfo; | ||
} | ||
) => { | ||
messages.push({ message, extra }); | ||
}; | ||
|
||
(transport["_stdin"] as Readable).emit( | ||
"data", | ||
Buffer.from( | ||
'{"jsonrpc":"2.0","id":1,"method":"testMethod","params":{"oid":{"$oid":"681b741f13aa74a0687b5110"},"uuid":{"$uuid":"f81d4fae-7dec-11d0-a765-00a0c91e6bf6"},"date":{"$date":"2025-05-07T14:54:23.973Z"},"decimal":{"$numberDecimal":"1234567890987654321"},"int32":123,"maxKey":{"$maxKey":1},"minKey":{"$minKey":1},"timestamp":{"$timestamp":{"t":123,"i":456}}}}\n', | ||
"utf-8" | ||
) | ||
); | ||
|
||
expect(messages.length).toBe(1); | ||
const message = messages[0].message; | ||
|
||
expect(message).toEqual({ | ||
jsonrpc: "2.0", | ||
id: 1, | ||
method: "testMethod", | ||
params: { | ||
oid: new ObjectId("681b741f13aa74a0687b5110"), | ||
uuid: new UUID("f81d4fae-7dec-11d0-a765-00a0c91e6bf6"), | ||
date: new Date(Date.parse("2025-05-07T14:54:23.973Z")), | ||
decimal: new Decimal128("1234567890987654321"), | ||
int32: 123, | ||
maxKey: new MaxKey(), | ||
minKey: new MinKey(), | ||
timestamp: new Timestamp({ t: 123, i: 456 }), | ||
}, | ||
}); | ||
}); | ||
|
||
it("has _readBuffer field of type EJsonReadBuffer", () => { | ||
expect(transport["_readBuffer"]).toBeDefined(); | ||
expect(transport["_readBuffer"]).toBeInstanceOf(EJsonReadBuffer); | ||
}); | ||
|
||
describe("standard StdioServerTransport", () => { | ||
it("has a _readBuffer field", () => { | ||
const standardTransport = new StdioServerTransport(); | ||
expect(standardTransport["_readBuffer"]).toBeDefined(); | ||
expect(standardTransport["_readBuffer"]).toBeInstanceOf(ReadBuffer); | ||
}); | ||
}); | ||
}); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[nitpick] Accessing a private property via server["_readBuffer"] may lead to maintainability issues if the underlying implementation changes. Consider exposing a dedicated method or refactoring the transport to safely update the read buffer.
Copilot uses AI. Check for mistakes.