-
Notifications
You must be signed in to change notification settings - Fork 125
Add MongoDB Assistant Tools #472
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
Open
nlarew
wants to merge
8
commits into
mongodb-js:main
Choose a base branch
from
nlarew:assistant-tool
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
2338504
(EAI-1266) Knowledge Search on MCP
nlarew 881c4ee
Add tests for assistant tools
nlarew 3bdd3df
Include server version in assistant user-agent header
nlarew 59b3c63
get server version from packageInfo
nlarew 34d50d8
Merge branch 'main' into assistant-tool
nlarew bb5e585
Review
nlarew d3b4d6b
Merge branch 'main' of github.com:mongodb-js/mongodb-mcp-server into …
nlarew 2736bca
Fix tests + move assistant request up to abstract base class
nlarew 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
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,51 @@ | ||
import { | ||
ToolBase, | ||
type TelemetryToolMetadata, | ||
type ToolArgs, | ||
type ToolCategory, | ||
type ToolConstructorParams, | ||
} from "../tool.js"; | ||
import { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; | ||
import { Server } from "../../server.js"; | ||
import { packageInfo } from "../../common/packageInfo.js"; | ||
|
||
export abstract class AssistantToolBase extends ToolBase { | ||
protected server?: Server; | ||
public category: ToolCategory = "assistant"; | ||
protected baseUrl: URL; | ||
protected requiredHeaders: Headers; | ||
|
||
constructor({ session, config, telemetry, elicitation }: ToolConstructorParams) { | ||
super({ session, config, telemetry, elicitation }); | ||
this.baseUrl = new URL(config.assistantBaseUrl); | ||
const serverVersion = packageInfo.version; | ||
this.requiredHeaders = new Headers({ | ||
"x-request-origin": "mongodb-mcp-server", | ||
"user-agent": serverVersion ? `mongodb-mcp-server/v${serverVersion}` : "mongodb-mcp-server", | ||
}); | ||
} | ||
|
||
public register(server: Server): boolean { | ||
this.server = server; | ||
return super.register(server); | ||
} | ||
|
||
protected resolveTelemetryMetadata(_args: ToolArgs<typeof this.argsShape>): TelemetryToolMetadata { | ||
// Assistant tool calls are not associated with a specific project or organization | ||
// Therefore, we don't have any values to add to the telemetry metadata | ||
return {}; | ||
} | ||
|
||
protected async callAssistantApi(args: { method: "GET" | "POST"; endpoint: string; body?: unknown }) { | ||
const endpoint = new URL(args.endpoint, this.baseUrl); | ||
const headers = new Headers(this.requiredHeaders); | ||
if (args.method === "POST") { | ||
headers.set("Content-Type", "application/json"); | ||
} | ||
return await fetch(endpoint, { | ||
method: args.method, | ||
headers, | ||
body: JSON.stringify(args.body), | ||
}); | ||
} | ||
} |
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,65 @@ | ||
import { z } from "zod"; | ||
nlarew marked this conversation as resolved.
Show resolved
Hide resolved
|
||
import { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; | ||
import { OperationType } from "../tool.js"; | ||
import { AssistantToolBase } from "./assistantTool.js"; | ||
import { LogId } from "../../common/logger.js"; | ||
|
||
export const dataSourceMetadataSchema = z.object({ | ||
id: z.string().describe("The name of the data source"), | ||
type: z.string().optional().describe("The type of the data source"), | ||
versions: z | ||
.array( | ||
z.object({ | ||
label: z.string().describe("The version label of the data source"), | ||
isCurrent: z.boolean().describe("Whether this version is current active version"), | ||
}) | ||
) | ||
.describe("A list of available versions for this data source"), | ||
}); | ||
|
||
export const listDataSourcesResponseSchema = z.object({ | ||
dataSources: z.array(dataSourceMetadataSchema).describe("A list of data sources"), | ||
}); | ||
|
||
export class ListKnowledgeSourcesTool extends AssistantToolBase { | ||
public name = "list-knowledge-sources"; | ||
protected description = "List available data sources in the MongoDB Assistant knowledge base"; | ||
protected argsShape = {}; | ||
public operationType: OperationType = "read"; | ||
|
||
protected async execute(): Promise<CallToolResult> { | ||
const response = await this.callAssistantApi({ | ||
method: "GET", | ||
endpoint: "content/sources", | ||
}); | ||
if (!response.ok) { | ||
const message = `Failed to list knowledge sources: ${response.statusText}`; | ||
this.session.logger.debug({ | ||
id: LogId.assistantListKnowledgeSourcesError, | ||
context: "assistant-list-knowledge-sources", | ||
message, | ||
}); | ||
return { | ||
content: [ | ||
{ | ||
type: "text", | ||
text: message, | ||
}, | ||
], | ||
isError: true, | ||
}; | ||
} | ||
const { dataSources } = listDataSourcesResponseSchema.parse(await response.json()); | ||
|
||
return { | ||
content: dataSources.map(({ id, type, versions }) => ({ | ||
type: "text", | ||
text: id, | ||
_meta: { | ||
type, | ||
versions, | ||
}, | ||
})), | ||
}; | ||
} | ||
} |
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,82 @@ | ||
import { z } from "zod"; | ||
import { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; | ||
import { ToolArgs, OperationType } from "../tool.js"; | ||
import { AssistantToolBase } from "./assistantTool.js"; | ||
import { LogId } from "../../common/logger.js"; | ||
|
||
export const SearchKnowledgeToolArgs = { | ||
query: z.string().describe("A natural language query to search for in the knowledge base"), | ||
limit: z.number().min(1).max(100).optional().default(5).describe("The maximum number of results to return"), | ||
nlarew marked this conversation as resolved.
Show resolved
Hide resolved
nlarew marked this conversation as resolved.
Show resolved
Hide resolved
nlarew marked this conversation as resolved.
Show resolved
Hide resolved
|
||
dataSources: z | ||
.array( | ||
z.object({ | ||
name: z.string().describe("The name of the data source"), | ||
versionLabel: z.string().optional().describe("The version label of the data source"), | ||
}) | ||
) | ||
.optional() | ||
.describe( | ||
"A list of one or more data sources to search in. You can specify a specific version of a data source by providing the version label. If not provided, the latest version of all data sources will be searched." | ||
), | ||
}; | ||
|
||
export const knowledgeChunkSchema = z | ||
.object({ | ||
url: z.string().describe("The URL of the search result"), | ||
title: z.string().describe("Title of the search result"), | ||
text: z.string().describe("Chunk text"), | ||
metadata: z | ||
.object({ | ||
tags: z.array(z.string()).describe("The tags of the source"), | ||
}) | ||
.passthrough(), | ||
}) | ||
.passthrough(); | ||
|
||
export const searchResponseSchema = z.object({ | ||
results: z.array(knowledgeChunkSchema).describe("A list of search results"), | ||
}); | ||
|
||
export class SearchKnowledgeTool extends AssistantToolBase { | ||
public name = "search-knowledge"; | ||
protected description = "Search for information in the MongoDB Assistant knowledge base"; | ||
protected argsShape = { | ||
...SearchKnowledgeToolArgs, | ||
}; | ||
public operationType: OperationType = "read"; | ||
|
||
protected async execute(args: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> { | ||
const response = await this.callAssistantApi({ | ||
method: "POST", | ||
endpoint: "content/search", | ||
body: args, | ||
}); | ||
if (!response.ok) { | ||
const message = `Failed to search knowledge base: ${response.statusText}`; | ||
this.session.logger.debug({ | ||
id: LogId.assistantSearchKnowledgeError, | ||
context: "assistant-search-knowledge", | ||
message, | ||
}); | ||
return { | ||
content: [ | ||
{ | ||
type: "text", | ||
text: message, | ||
}, | ||
], | ||
isError: true, | ||
}; | ||
} | ||
const { results } = searchResponseSchema.parse(await response.json()); | ||
return { | ||
content: results.map(({ text, metadata }) => ({ | ||
type: "text", | ||
text, | ||
_meta: { | ||
...metadata, | ||
}, | ||
})), | ||
}; | ||
} | ||
} |
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,4 @@ | ||
import { ListKnowledgeSourcesTool } from "./listKnowledgeSources.js"; | ||
import { SearchKnowledgeTool } from "./searchKnowledge.js"; | ||
|
||
export const AssistantTools = [ListKnowledgeSourcesTool, SearchKnowledgeTool]; |
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 |
---|---|---|
|
@@ -16,7 +16,7 @@ export type ToolCallbackArgs<Args extends ZodRawShape> = Parameters<ToolCallback | |
export type ToolExecutionContext<Args extends ZodRawShape = ZodRawShape> = Parameters<ToolCallback<Args>>[1]; | ||
|
||
export type OperationType = "metadata" | "read" | "create" | "delete" | "update" | "connect"; | ||
export type ToolCategory = "mongodb" | "atlas"; | ||
export type ToolCategory = "mongodb" | "atlas" | "assistant"; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. since we're here, can we also update the readme.md? there we call out all the tool categories |
||
export type TelemetryToolMetadata = { | ||
projectId?: string; | ||
orgId?: string; | ||
|
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
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.
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.
Not sure what if anything I should have here - would appreciate advice from the DevTools team on this.
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.
The
TelemetryToolMetadata
type seems to track a specific Atlas org/project but the assistant is not associated with a given Atlas instance. Planning to leave this empty unless someone has a good idea of what to put here.