-
Notifications
You must be signed in to change notification settings - Fork 1k
[MCP] implement {get,set}_data and {validate,get}_rules for RTDB MCP #8854
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
+323
−5
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
9725bbc
implement mcp logging
da45a6b
some in-line docs for the mcp tool
5034ab7
[MCP] implement {get,set}_data and {validate,get}_rules for RTDB MCP
b265398
review round 1: use path.join, fix mismatched url
3c5b85d
merge w master
00d7692
fix another typo I missed
671f284
fix import to not have js suffix
79c101b
Merge branch 'master' into oleina/rtdbmcp
joehan ec01b0d
Merge branch 'master' into oleina/rtdbmcp
antholeole 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
import { z } from "zod"; | ||
import { tool } from "../../tool"; | ||
import { mcpError, toContent } from "../../util"; | ||
import * as url from "node:url"; | ||
import { Client } from "../../../apiv2"; | ||
import { text } from "node:stream/consumers"; | ||
import path from "node:path"; | ||
|
||
export const get_data = tool( | ||
{ | ||
name: "get_data", | ||
description: "Returns RTDB data from the specified location", | ||
inputSchema: z.object({ | ||
databaseUrl: z | ||
.string() | ||
.optional() | ||
.describe( | ||
"connect to the database at url. If omitted, use default database instance <project>-default-rtdb.firebasedatabase.app. Can point to emulator URL (e.g. localhost:6000/<instance>)", | ||
), | ||
path: z.string().describe("The path to the data to read. (ex: /my/cool/path)"), | ||
}), | ||
annotations: { | ||
title: "Get Realtime Database data", | ||
readOnlyHint: true, | ||
}, | ||
|
||
_meta: { | ||
// it's possible that a user attempts to query a database that they aren't | ||
// authed into: we should let the rules evaluate as the author intended. | ||
// If they have written rules to leave paths public, then having mcp | ||
// grab their data is perfectly valid. | ||
requiresAuth: false, | ||
requiresProject: false, | ||
}, | ||
}, | ||
async ({ path: getPath, databaseUrl }, { projectId, host }) => { | ||
if (!getPath.startsWith("/")) { | ||
return mcpError(`paths must start with '/' (you passed ''${getPath}')`); | ||
} | ||
|
||
const dbUrl = new url.URL( | ||
databaseUrl | ||
? `${databaseUrl}/${getPath}.json` | ||
: path.join( | ||
`https://${projectId}-default-rtdb.us-central1.firebasedatabase.app`, | ||
`${getPath}.json`, | ||
), | ||
); | ||
|
||
const client = new Client({ | ||
urlPrefix: dbUrl.origin, | ||
auth: true, | ||
}); | ||
|
||
host.logger.debug(`sending read request to path '${getPath}' for url '${dbUrl.toString()}'`); | ||
|
||
const res = await client.request<unknown, NodeJS.ReadableStream>({ | ||
method: "GET", | ||
path: dbUrl.pathname, | ||
responseType: "stream", | ||
resolveOnHTTPError: true, | ||
}); | ||
|
||
const content = await text(res.body); | ||
return toContent(content); | ||
}, | ||
); |
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,46 @@ | ||
import { z } from "zod"; | ||
import { Client } from "../../../apiv2"; | ||
import { tool } from "../../tool"; | ||
import { mcpError, toContent } from "../../util"; | ||
|
||
export const get_rules = tool( | ||
{ | ||
name: "get_rules", | ||
description: "Get an RTDB database's rules", | ||
inputSchema: z.object({ | ||
databaseUrl: z | ||
.string() | ||
.optional() | ||
.describe( | ||
"connect to the database at url. If omitted, use default database instance <project>-default-rtdb.firebaseio.com. Can point to emulator URL (e.g. localhost:6000/<instance>)", | ||
), | ||
}), | ||
annotations: { | ||
title: "Get Realtime Database rules", | ||
readOnlyHint: true, | ||
}, | ||
|
||
_meta: { | ||
requiresAuth: false, | ||
requiresProject: false, | ||
}, | ||
}, | ||
async ({ databaseUrl }, { projectId }) => { | ||
const dbUrl = | ||
databaseUrl ?? `https://${projectId}-default-rtdb.us-central1.firebasedatabase.app`; | ||
antholeole marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
const client = new Client({ urlPrefix: dbUrl }); | ||
const response = await client.request<void, NodeJS.ReadableStream>({ | ||
method: "GET", | ||
path: "/.settings/rules.json", | ||
responseType: "stream", | ||
resolveOnHTTPError: true, | ||
}); | ||
if (response.status !== 200) { | ||
return mcpError(`Failed to fetch current rules. Code: ${response.status}`); | ||
} | ||
|
||
const rules = await response.response.text(); | ||
antholeole marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return toContent(rules); | ||
}, | ||
); |
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,7 @@ | ||
import type { ServerTool } from "../../tool"; | ||
import { get_rules } from "./get_rules"; | ||
import { get_data } from "./get_data"; | ||
import { set_data } from "./set_data"; | ||
import { validate_rules } from "./validate_rules"; | ||
|
||
export const realtimeDatabaseTools: ServerTool[] = [get_data, set_data, get_rules, validate_rules]; |
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 { z } from "zod"; | ||
import { tool } from "../../tool"; | ||
import { mcpError, toContent } from "../../util"; | ||
import * as url from "node:url"; | ||
import { stringToStream } from "../../../utils"; | ||
import { Client } from "../../../apiv2"; | ||
import { getErrMsg } from "../../../error"; | ||
import path from "node:path"; | ||
|
||
export const set_data = tool( | ||
{ | ||
name: "set_data", | ||
description: "Writes RTDB data to the specified location", | ||
inputSchema: z.object({ | ||
databaseUrl: z | ||
.string() | ||
.optional() | ||
.describe( | ||
"connect to the database at url. If omitted, use default database instance <project>-default-rtdb.us-central1.firebasedatabase.app. Can point to emulator URL (e.g. localhost:6000/<instance>)", | ||
), | ||
path: z.string().describe("The path to the data to read. (ex: /my/cool/path)"), | ||
data: z.string().describe('The JSON to write. (ex: {"alphabet": ["a", "b", "c"]})'), | ||
}), | ||
annotations: { | ||
title: "Set Realtime Database data", | ||
readOnlyHint: false, | ||
idempotentHint: true, | ||
}, | ||
|
||
_meta: { | ||
requiresAuth: false, | ||
requiresProject: false, | ||
}, | ||
}, | ||
async ({ path: setPath, databaseUrl, data }, { projectId, host }) => { | ||
if (!setPath.startsWith("/")) { | ||
return mcpError(`paths must start with '/' (you passed ''${setPath}')`); | ||
} | ||
|
||
const dbUrl = new url.URL( | ||
databaseUrl | ||
? `${databaseUrl}/${setPath}.json` | ||
: path.join( | ||
`https://${projectId}-default-rtdb.us-central1.firebasedatabase.app`, | ||
`${setPath}.json`, | ||
), | ||
); | ||
|
||
const client = new Client({ | ||
urlPrefix: dbUrl.origin, | ||
auth: true, | ||
}); | ||
|
||
const inStream = stringToStream(data); | ||
|
||
host.logger.debug(`sending write request to path '${setPath}' for url '${dbUrl.toString()}'`); | ||
|
||
try { | ||
await client.request({ | ||
method: "PUT", | ||
path: dbUrl.pathname, | ||
body: inStream, | ||
}); | ||
} catch (err: unknown) { | ||
host.logger.debug(getErrMsg(err)); | ||
return mcpError(`Unexpected error while setting data: ${getErrMsg(err)}`); | ||
} | ||
|
||
return toContent("write successful!"); | ||
}, | ||
); |
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,48 @@ | ||
import { z } from "zod"; | ||
import { Client } from "../../../apiv2"; | ||
import { tool } from "../../tool"; | ||
import { mcpError, toContent } from "../../util"; | ||
import { updateRulesWithClient } from "../../../rtdb"; | ||
import { getErrMsg } from "../../../error"; | ||
|
||
export const validate_rules = tool( | ||
{ | ||
name: "validate_rules", | ||
description: "Validates an RTDB database's rules", | ||
inputSchema: z.object({ | ||
databaseUrl: z | ||
.string() | ||
.optional() | ||
.describe( | ||
"connect to the database at url. If omitted, use default database instance <project>-default-rtdb.firebaseio.com. Can point to emulator URL (e.g. localhost:6000/<instance>)", | ||
), | ||
rules: z | ||
.string() | ||
.describe('The rules object, as a string (ex: {".read": false, ".write": false})'), | ||
}), | ||
annotations: { | ||
title: "Validate Realtime Database rules", | ||
idempotentHint: true, | ||
}, | ||
|
||
_meta: { | ||
requiresAuth: true, | ||
requiresProject: false, | ||
}, | ||
}, | ||
async ({ databaseUrl, rules }, { projectId, host }) => { | ||
const dbUrl = | ||
databaseUrl ?? `https://${projectId}-default-rtdb.us-central1.firebasedatabase.app`; | ||
|
||
const client = new Client({ urlPrefix: dbUrl }); | ||
|
||
try { | ||
await updateRulesWithClient(client, rules, { dryRun: true }); | ||
} catch (e: unknown) { | ||
host.logger.debug(`failed to update rules at url ${dbUrl}`); | ||
return mcpError(getErrMsg(e)); | ||
} | ||
|
||
return toContent("the inputted rules are valid!"); | ||
}, | ||
); | ||
antholeole marked this conversation as resolved.
Show resolved
Hide resolved
|
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,50 @@ | ||
import { z } from "zod"; | ||
import { Client } from "../../../apiv2"; | ||
import { tool } from "../../tool"; | ||
import { mcpError, toContent } from "../../util"; | ||
import { updateRulesWithClient } from "../../../rtdb"; | ||
import { getErrMsg } from "../../../error"; | ||
|
||
export const validate_rules = tool( | ||
{ | ||
name: "validate_rules", | ||
description: "Validates an RTDB database's rules", | ||
inputSchema: z.object({ | ||
databaseUrl: z | ||
.string() | ||
.optional() | ||
.describe( | ||
"connect to the database at url. If omitted, use default database instance <project>-default-rtdb.firebaseio.com. Can point to emulator URL (e.g. localhost:6000/<instance>)", | ||
), | ||
rules: z | ||
.string() | ||
.describe( | ||
'The rules object, as a string (ex: {"rules": {".read": false, ".write": false}})', | ||
), | ||
}), | ||
annotations: { | ||
title: "Validate Realtime Database rules", | ||
idempotentHint: true, | ||
}, | ||
|
||
_meta: { | ||
requiresAuth: true, | ||
requiresProject: false, | ||
}, | ||
}, | ||
async ({ databaseUrl, rules }, { projectId, host }) => { | ||
const dbUrl = | ||
databaseUrl ?? `https://${projectId}-default-rtdb.us-central1.firebasedatabase.app`; | ||
antholeole marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
const client = new Client({ urlPrefix: dbUrl }); | ||
|
||
try { | ||
await updateRulesWithClient(client, rules, { dryRun: true }); | ||
} catch (e: unknown) { | ||
host.logger.debug(`failed to validate rules at url ${dbUrl}`); | ||
return mcpError(getErrMsg(e)); | ||
} | ||
|
||
return toContent("the inputted rules are valid!"); | ||
}, | ||
); |
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
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.