Repository navigation
refactor(mcp): cleanup auth and reorganize tools - #979
Conversation
Better Auth's consent endpoint doesn't accept scope in the body, so the organization scope selected on the consent screen was being ignored. - Add custom /oauth/add-org-scope endpoint that updates the verification value with the organization scope before consent is processed - Update consent form to call this endpoint before submitting consent - Add KV_URL to env and deployment workflows for Redis connection - Remove fallback logic that looked up a random organization
📝 WalkthroughWalkthroughHigh-level changes: Added KV_URL env propagation in GH workflows; replaced Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant API
participant DB as Database
participant Agent as Device/Agent
Client->>API: call tool endpoint (e.g., create_workspace)
API->>API: registerTool wrapper validates auth (extract mcpContext)
API->>DB: check device presence (devicePresence by deviceId)
alt device offline
API-->>Client: return { isError: true, message: "device offline" }
else device online
API->>DB: insert agentCommand (status: pending, params, timeoutAt)
API->>DB: poll agentCommand status periodically
Agent->>DB: update agentCommand status to "completed" or "failed" with result
DB-->>API: poll sees "completed" -> returns result
API-->>Client: respond with tool result payload
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
🧹 Preview Cleanup CompleteThe following preview resources have been cleaned up:
Thank you for your contribution! 🎉 |
There was a problem hiding this comment.
Actionable comments posted: 8
🤖 Fix all issues with AI agents
In `@apps/api/src/lib/mcp/tools/devices/create-workspace/create-workspace.ts`:
- Around line 22-25: The input schema declares taskId but it is never forwarded
to executeOnDevice; update the params object (the one passed into
executeOnDevice) to include taskId from the handler input (preserve optional
behavior), e.g., add taskId: input.taskId (or equivalent variable) to the params
passed to executeOnDevice so create-workspace logic receives the task
association; locate the params construction and the executeOnDevice call in
create-workspace.ts and add the field there.
In `@apps/api/src/lib/mcp/tools/organizations/list-members/list-members.ts`:
- Around line 48-51: The LIKE pattern currently interpolates raw user input into
ilike(users.name, `%${search}%`) allowing wildcard injection; add a helper
(e.g., escapeLikePattern) that escapes %, _, and backslash in the incoming
search string, call it before building the pattern, and use the escaped value in
the ilike calls (e.g., ilike(users.name, `%${escaped}%`) and ilike(users.email,
`%${escaped}%`) so user-supplied %/_ do not act as wildcards while keeping
parameterization intact.
In `@apps/api/src/lib/mcp/tools/tasks/create-task/create-task.ts`:
- Around line 129-145: The current return builds JSON from result.task using
optional chaining, which can produce undefined fields if no row was inserted;
update the create-task logic to explicitly check if result.task exists (inspect
result.task) before constructing the response and handle the missing-case by
either throwing a descriptive error or returning an error payload that includes
result.txid and a clear failure message; ensure you update the return block that
currently JSON.stringify({ id: result.task?.id, slug: result.task?.slug, title:
result.task?.title, txid: result.txid }) to only read id/slug/title when
result.task is present and to provide a deterministic fallback otherwise.
In `@apps/api/src/lib/mcp/tools/tasks/delete-task/delete-task.ts`:
- Around line 42-64: The response uses a different new Date() than the one
persisted; fix by generating a single deletedAt timestamp and using it both in
the transaction update (tx.update(tasks).set({ deletedAt })) and in the returned
JSON (replacing the separate new Date().toISOString()), ensuring you still call
getCurrentTxid(tx) and return result.txid from dbWs.transaction so the persisted
timestamp and the response timestamp match.
In `@apps/api/src/lib/mcp/tools/tasks/update-task/update-task.ts`:
- Around line 75-83: After the transaction returns, add a post-transaction guard
that checks whether result.task is undefined (i.e., the UPDATE affected zero
rows) and if so convert that case into a not-found error instead of returning
success; specifically, after the dbWs.transaction(...) call that returns { task,
txid } from the inner tx update, verify the returned task exists and throw or
return a 404/not-found error (using the same error type/flow the service uses)
referencing the existingTask.id so callers know which id was missing.
- Around line 60-73: The update handler builds updateData from params but
doesn't guard against an empty payload, causing Drizzle's .set() to throw "No
values to set"; before calling the DB update (where updateData is used, e.g., in
the function that constructs updateData in update-task.ts), check if
Object.keys(updateData).length === 0 and return an early error (or throw a
controlled error/BadRequest) indicating no updatable fields were provided so the
code never calls the DB with an empty object; reference the updateData variable
and the params input to implement this validation.
In `@apps/api/src/lib/mcp/tools/utils/execute-on-device.ts`:
- Around line 106-109: The unconditional update using
db.update(agentCommands).set({ status: "timeout" }).where(eq(agentCommands.id,
cmd.id)) can overwrite a command that finished just before the timeout; change
it to first read the current status for the specific command id (eg. query
agentCommands where id == cmd.id), and only perform the update to status =
"timeout" if the current status is still a pending/running state (not
"completed", "failed", or other final states). Use the same unique symbols
(agentCommands, cmd.id, db) and perform the conditional update transactionally
or by adding the current-status check in the WHERE clause to avoid race
conditions.
In `@packages/auth/src/lib/oauth-org-scope-endpoint.ts`:
- Around line 59-84: When parsing verification.value in the oauth-org-scope
logic, guard JSON.parse and log parse failures with a prefixed message (e.g.,
"oauth-org-scope: failed to parse verification value") instead of letting it
throw; then ensure you replace any existing organization:* scope rather than
skipping when one already exists: parse verification.value into value, normalize
value.scope into an array (currentScopes), remove any entries that
startWith("organization:"), push the new orgScope
(`organization:${organizationId}`), and write back via
db.update(verifications).set({ value: JSON.stringify({...value, scope:
currentScopes}) }).where(eq(verifications.id, verification.id)).
🧹 Nitpick comments (9)
apps/api/src/env.ts (1)
31-33: Consider aligning URL validation across KV variables.
KV_URLuses.url()validation whileKV_REST_API_URLon line 31 does not. If both are expected to be valid URLs, consider adding.url()toKV_REST_API_URLfor consistency.Suggested alignment
- KV_REST_API_URL: z.string(), + KV_REST_API_URL: z.string().url(), KV_REST_API_TOKEN: z.string(), KV_URL: z.string().url(),apps/api/src/lib/mcp/tools/devices/list-workspaces/list-workspaces.ts (1)
13-20: Consider removing redundant validation or enforcing non-empty at schema level.Since
z.string()already rejectsundefined/null, Zod validation should fail before the handler runs ifdeviceIdis missing. Theas stringcast and subsequent check are redundant for that case.If the intent is to reject empty strings, use
z.string().min(1)in the schema (line 9) for clearer validation at the boundary.Suggested schema-level validation
inputSchema: { - deviceId: z.string().describe("Target device ID"), + deviceId: z.string().min(1).describe("Target device ID"), },Then remove the redundant handler check:
async (params, ctx) => { - const deviceId = params.deviceId as string; - - if (!deviceId) { - return { - content: [{ type: "text", text: "Error: deviceId is required" }], - isError: true, - }; - } + const { deviceId } = params; return executeOnDevice({apps/api/src/app/api/agent/[transport]/route.ts (1)
66-66: Simplify callback to direct function reference.The wrapper function is unnecessary since
registerToolsalready has the expected signature.Suggested change
const baseHandler = createMcpHandler( - (server) => registerTools(server), + registerTools, { capabilities: { tools: {} } },apps/api/src/lib/mcp/tools/devices/create-workspace/create-workspace.ts (1)
29-36: Redundant validation: Zod schema already enforcesdeviceIdas required.The
z.string()schema fordeviceIdensures it cannot be undefined. The manualif (!deviceId)check is defensive but technically unnecessary. This pattern is consistent across other device tools, so keeping it for defense-in-depth is acceptable.apps/api/src/lib/mcp/tools/tasks/create-task/create-task.ts (1)
90-105: Slug uniqueness query may fetch more rows than necessary.The
ilike(tasks.slug, \${baseSlug}%`)query matches any slug starting withbaseSlug, potentially including unrelated slugs (e.g.,baseSlug="task"matches both"task-1"and"task-unrelated-feature"). The logic is correct since theSetcheck verifies exact matches, but a more precise pattern like${baseSlug}or${baseSlug}-[0-9]+` would reduce unnecessary data transfer.apps/api/src/lib/mcp/tools/utils/register-tool.ts (1)
29-31: Consider adding logging before throwing the authentication error.Per coding guidelines, errors should be logged with context. Adding a log statement would help with debugging authentication issues in production.
♻️ Proposed enhancement
const ctx = authInfo?.extra?.mcpContext; if (!ctx) { + console.error("[mcp/register-tool] No MCP context available - authentication required"); throw new Error("No MCP context available - authentication required"); }apps/api/src/lib/mcp/tools/organizations/list-members/list-members.ts (1)
21-55: Query construction is duplicated; consider using a dynamic approach.The select clause and join are duplicated between the base query (lines 21-32) and the search-filtered query (lines 35-54). A dynamic where clause builder would reduce duplication and maintenance burden.
♻️ Simplified approach using dynamic conditions
- let query = db - .select({ - id: users.id, - name: users.name, - email: users.email, - image: users.image, - role: members.role, - }) - .from(members) - .innerJoin(users, eq(members.userId, users.id)) - .where(and(...conditions)) - .limit(limit); - - if (search) { - query = db - .select({ - id: users.id, - name: users.name, - email: users.email, - image: users.image, - role: members.role, - }) - .from(members) - .innerJoin(users, eq(members.userId, users.id)) - .where( - and( - ...conditions, - or( - ilike(users.name, `%${search}%`), - ilike(users.email, `%${search}%`), - ), - ), - ) - .limit(limit); - } + if (search) { + conditions.push( + or( + ilike(users.name, `%${search}%`), + ilike(users.email, `%${search}%`), + )!, + ); + } + + const query = db + .select({ + id: users.id, + name: users.name, + email: users.email, + image: users.image, + role: members.role, + }) + .from(members) + .innerJoin(users, eq(members.userId, users.id)) + .where(and(...conditions)) + .limit(limit);apps/api/src/lib/mcp/tools/tasks/get-task/get-task.ts (1)
12-14: Consider adding.min(1)to thetaskIdschema to reject empty strings.The current
z.string()allows empty strings, which would fail the UUID check and fall back to slug lookup with an empty string. Adding.min(1)would provide clearer validation.♻️ Proposed schema enhancement
inputSchema: { - taskId: z.string().describe("Task ID (uuid) or slug"), + taskId: z.string().min(1).describe("Task ID (uuid) or slug"), },apps/api/src/lib/mcp/tools/devices/list-devices/list-devices.ts (1)
20-31: Extract the offline window multiplier into a named constant.Helps avoid magic numbers and makes the intent clearer. As per coding guidelines, avoid magic numbers.
♻️ Suggested refactor
+const OFFLINE_THRESHOLD_MULTIPLIER = 10; + const threshold = new Date(Date.now() - DEVICE_ONLINE_THRESHOLD_MS); const offlineThreshold = new Date( - Date.now() - DEVICE_ONLINE_THRESHOLD_MS * 10, + Date.now() - DEVICE_ONLINE_THRESHOLD_MS * OFFLINE_THRESHOLD_MULTIPLIER, );
| or( | ||
| ilike(users.name, `%${search}%`), | ||
| ilike(users.email, `%${search}%`), | ||
| ), |
There was a problem hiding this comment.
User input in LIKE pattern allows wildcard injection.
The search parameter is interpolated directly into the LIKE pattern (%${search}%). While Drizzle parameterizes values preventing SQL injection, a user can still inject LIKE wildcards (e.g., % or _) to alter query behavior. Consider escaping LIKE special characters if strict matching is desired.
♻️ Optional: Escape LIKE wildcards
// Helper to escape LIKE special characters
function escapeLikePattern(str: string): string {
return str.replace(/[%_\\]/g, '\\$&');
}
// Usage
const escaped = escapeLikePattern(search);
ilike(users.name, `%${escaped}%`)🤖 Prompt for AI Agents
In `@apps/api/src/lib/mcp/tools/organizations/list-members/list-members.ts` around
lines 48 - 51, The LIKE pattern currently interpolates raw user input into
ilike(users.name, `%${search}%`) allowing wildcard injection; add a helper
(e.g., escapeLikePattern) that escapes %, _, and backslash in the incoming
search string, call it before building the pattern, and use the escaped value in
the ilike calls (e.g., ilike(users.name, `%${escaped}%`) and ilike(users.email,
`%${escaped}%`) so user-supplied %/_ do not act as wildcards while keeping
parameterization intact.
| const result = await dbWs.transaction(async (tx) => { | ||
| const [task] = await tx | ||
| .update(tasks) | ||
| .set(updateData) | ||
| .where(eq(tasks.id, existingTask.id)) | ||
| .returning(); | ||
|
|
||
| const txid = await getCurrentTxid(tx); | ||
| return { task, txid }; |
There was a problem hiding this comment.
Handle zero-row updates inside the transaction.
If the task is deleted between the initial read and the UPDATE, result.task can be undefined and the response will still look successful. Consider a post-transaction guard to return a not‑found error instead.
🧯 Guard against missing updated row
const result = await dbWs.transaction(async (tx) => {
const [task] = await tx
.update(tasks)
.set(updateData)
.where(eq(tasks.id, existingTask.id))
.returning();
const txid = await getCurrentTxid(tx);
return { task, txid };
});
+
+ if (!result.task) {
+ return {
+ content: [{ type: "text", text: "Error: Task not found" }],
+ isError: true,
+ };
+ }🤖 Prompt for AI Agents
In `@apps/api/src/lib/mcp/tools/tasks/update-task/update-task.ts` around lines 75
- 83, After the transaction returns, add a post-transaction guard that checks
whether result.task is undefined (i.e., the UPDATE affected zero rows) and if so
convert that case into a not-found error instead of returning success;
specifically, after the dbWs.transaction(...) call that returns { task, txid }
from the inner tx update, verify the returned task exists and throw or return a
404/not-found error (using the same error type/flow the service uses)
referencing the existingTask.id so callers know which id was missing.
| // Parse the stored value and add organization scope | ||
| const value = JSON.parse(verification.value); | ||
| const orgScope = `organization:${organizationId}`; | ||
|
|
||
| // Ensure scope is an array | ||
| const currentScopes = Array.isArray(value.scope) | ||
| ? value.scope | ||
| : typeof value.scope === "string" | ||
| ? value.scope.split(" ") | ||
| : []; | ||
|
|
||
| // Add org scope if not already present | ||
| if (!currentScopes.some((s: string) => s.startsWith("organization:"))) { | ||
| currentScopes.push(orgScope); | ||
| } | ||
|
|
||
| // Update the verification value with the new scopes | ||
| await db | ||
| .update(verifications) | ||
| .set({ | ||
| value: JSON.stringify({ | ||
| ...value, | ||
| scope: currentScopes, | ||
| }), | ||
| }) | ||
| .where(eq(verifications.id, verification.id)); |
There was a problem hiding this comment.
Replace existing organization scopes and guard malformed verification payloads.
If a consent code already contains an organization: scope and the user changes selection, the current check skips updating the scope, so consent can be applied to the wrong org. Also, JSON.parse can throw on a corrupted verification value; handle it explicitly and log with a prefix. As per coding guidelines, log parse failures with a prefixed message.
🛠️ Suggested fix
- const value = JSON.parse(verification.value);
+ let value: { scope?: string | string[] } = {};
+ try {
+ value = JSON.parse(verification.value);
+ } catch (err) {
+ console.error(
+ "[auth/oauth] Failed to parse consent verification value",
+ err,
+ );
+ return ctx.json({ error: "Invalid consent payload" }, { status: 400 });
+ }
@@
- const currentScopes = Array.isArray(value.scope)
+ const currentScopes = Array.isArray(value.scope)
? value.scope
: typeof value.scope === "string"
? value.scope.split(" ")
: [];
-
- // Add org scope if not already present
- if (!currentScopes.some((s: string) => s.startsWith("organization:"))) {
- currentScopes.push(orgScope);
- }
+ const normalizedScopes = currentScopes.filter(
+ (s: string) => !s.startsWith("organization:"),
+ );
+ normalizedScopes.push(orgScope);
@@
- scope: currentScopes,
+ scope: normalizedScopes,🤖 Prompt for AI Agents
In `@packages/auth/src/lib/oauth-org-scope-endpoint.ts` around lines 59 - 84, When
parsing verification.value in the oauth-org-scope logic, guard JSON.parse and
log parse failures with a prefixed message (e.g., "oauth-org-scope: failed to
parse verification value") instead of letting it throw; then ensure you replace
any existing organization:* scope rather than skipping when one already exists:
parse verification.value into value, normalize value.scope into an array
(currentScopes), remove any entries that startWith("organization:"), push the
new orgScope (`organization:${organizationId}`), and write back via
db.update(verifications).set({ value: JSON.stringify({...value, scope:
currentScopes}) }).where(eq(verifications.id, verification.id)).
- Forward taskId parameter in create-workspace tool - Add explicit error handling when task insert returns nothing - Use single timestamp for deletedAt in delete-task - Validate updateData is not empty before DB update in update-task - Add status check to timeout update to prevent race condition - Add JSON.parse error guard in oauth-org-scope endpoint
Summary
@vercel/mcp-adapterwithmcp-handlerpackagetools.ts(1126 lines) into domain folders per AGENTS.md co-location guidelinesregisterToolhelper for cleaner tool registrationMcpContextto only required fields (userId, organizationId)Changes
Package & Config
@vercel/mcp-adapterwithmcp-handlerKV_URLto env validation and deployment workflowsAuth Simplification
auth.tsto just theMcpContextinterfaceroute.tsauth logicTool Reorganization
OAuth Scope Fix
Better Auth's consent endpoint doesn't accept
scopein the body, so the organization scope selected on the consent screen was being ignored./oauth/add-org-scopeendpoint that updates the verification value before consentTest plan
bun run lint:fix- passes (only expected warnings)bun run typecheck- passesbun test- 1193 pass, 7 skipSummary by CodeRabbit
New Features
Refactor
Chores
✏️ Tip: You can customize this high-level summary in your review settings.