Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 13 additions & 11 deletions open-sse/mcp-server/scopeEnforcement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,26 +99,28 @@ export function resolveCallerScopeContext(
export function evaluateToolScopes(
toolName: string,
callerScopes: readonly string[],
enforceScopes: boolean
enforceScopes: boolean,
inlineScopes?: readonly string[]
): ScopeCheckResult {
const toolDef = MCP_TOOL_MAP[toolName];
if (!toolDef) {
const provided = normalizeScopeList(callerScopes);

if (!enforceScopes) {
return { allowed: true, required: [], provided, missing: [] };
}

const toolScopes = inlineScopes ?? MCP_TOOL_MAP[toolName]?.scopes;
const required = Array.isArray(toolScopes) ? Array.from(toolScopes) : [];

if (required.length === 0) {
return {
allowed: false,
required: [],
provided: Array.from(callerScopes),
provided,
missing: [],
reason: "tool_definition_missing",
};
}
Comment on lines +111 to 122

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

The current implementation treats any tool with an empty scopes list (required.length === 0) as having a missing tool definition, returning allowed: false with reason: "tool_definition_missing". This blocks any tool that explicitly requires no scopes (e.g., scopes: []).

Instead, we should check if toolScopes is undefined to determine if the tool definition is missing. If toolScopes is defined (even if it is an empty array), and no scopes are required, the tool should be allowed.

Suggested change
const toolScopes = inlineScopes ?? MCP_TOOL_MAP[toolName]?.scopes;
const required = Array.isArray(toolScopes) ? Array.from(toolScopes) : [];
if (required.length === 0) {
return {
allowed: false,
required: [],
provided: Array.from(callerScopes),
provided,
missing: [],
reason: "tool_definition_missing",
};
}
const toolScopes = inlineScopes ?? MCP_TOOL_MAP[toolName]?.scopes;
if (toolScopes === undefined) {
return {
allowed: false,
required: [],
provided,
missing: [],
reason: "tool_definition_missing",
};
}
const required = Array.isArray(toolScopes) ? Array.from(toolScopes) : [];


const required = Array.isArray(toolDef.scopes) ? Array.from(toolDef.scopes) : [];
const provided = normalizeScopeList(callerScopes);

if (!enforceScopes || required.length === 0) {
return { allowed: true, required, provided, missing: [] };
}

const missing = required.filter(
(requiredScope) => !provided.some((grantedScope) => scopeMatches(grantedScope, requiredScope))
);
Expand Down
141 changes: 81 additions & 60 deletions open-sse/mcp-server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,11 +203,12 @@ async function omniRouteFetch(path: string, options: RequestInit = {}): Promise<

function withScopeEnforcement(
toolName: string,
handler: (args: unknown, extra?: McpToolExtraLike) => Promise<TextToolResult>
handler: (args: unknown, extra?: McpToolExtraLike) => Promise<TextToolResult>,
toolScopes?: readonly string[]
) {
return async (args: unknown, extra?: McpToolExtraLike): Promise<TextToolResult> => {
const scopeContext = resolveCallerScopeContext(extra, Array.from(MCP_ALLOWED_SCOPES));
const scopeCheck = evaluateToolScopes(toolName, scopeContext.scopes, MCP_ENFORCE_SCOPES);
const scopeCheck = evaluateToolScopes(toolName, scopeContext.scopes, MCP_ENFORCE_SCOPES, toolScopes);
if (!scopeCheck.allowed) {
const missingScopes =
scopeCheck.missing.length > 0 ? scopeCheck.missing.join(", ") : "unavailable";
Expand Down Expand Up @@ -960,48 +961,56 @@ export function createMcpServer(): McpServer {
);

// ── Memory Tools ──────────────────────────────
Object.values(memoryTools).forEach((toolDef) => {
Object.values(memoryTools).forEach((toolDef: any) => {
server.registerTool(
toolDef.name,
{
description: toolDef.description,
// @ts-ignore: dynamic zod access
inputSchema: toolDef.inputSchema,
},
withScopeEnforcement(toolDef.name, async (args) => {
try {
const parsedArgs = toolDef.inputSchema.parse(args ?? {});
// @ts-expect-error - handler type lost through dynamic Object.values() access
const result = await toolDef.handler(parsedArgs);
return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
return { content: [{ type: "text" as const, text: `Error: ${msg}` }], isError: true };
}
})
withScopeEnforcement(
toolDef.name,
async (args) => {
try {
const parsedArgs = toolDef.inputSchema.parse(args ?? {});
// @ts-expect-error - handler type lost through dynamic Object.values() access
const result = await toolDef.handler(parsedArgs);
return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
return { content: [{ type: "text" as const, text: `Error: ${msg}` }], isError: true };
}
},
toolDef.scopes
)
);
});

// ── Skill Tools ──────────────────────────────
Object.values(skillTools).forEach((toolDef) => {
Object.values(skillTools).forEach((toolDef: any) => {
server.registerTool(
toolDef.name,
{
description: toolDef.description,
// @ts-ignore: dynamic zod access
inputSchema: toolDef.inputSchema,
},
withScopeEnforcement(toolDef.name, async (args) => {
try {
const parsedArgs = toolDef.inputSchema.parse(args ?? {});
// @ts-expect-error - handler type lost through dynamic Object.values() access
const result = await toolDef.handler(parsedArgs);
return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
return { content: [{ type: "text" as const, text: `Error: ${msg}` }], isError: true };
}
})
withScopeEnforcement(
toolDef.name,
async (args) => {
try {
const parsedArgs = toolDef.inputSchema.parse(args ?? {});
// @ts-expect-error - handler type lost through dynamic Object.values() access
const result = await toolDef.handler(parsedArgs);
return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
return { content: [{ type: "text" as const, text: `Error: ${msg}` }], isError: true };
}
},
toolDef.scopes
)
);
});

Expand All @@ -1014,40 +1023,48 @@ export function createMcpServer(): McpServer {
// @ts-ignore: dynamic zod access
inputSchema: toolDef.inputSchema,
},
withScopeEnforcement(toolDef.name, async (args) => {
try {
const parsedArgs = toolDef.inputSchema.parse(args ?? {});
// @ts-ignore: handler expected specific object
const result = await toolDef.handler(parsedArgs);
return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
return { content: [{ type: "text" as const, text: `Error: ${msg}` }], isError: true };
}
})
withScopeEnforcement(
toolDef.name,
async (args) => {
try {
const parsedArgs = toolDef.inputSchema.parse(args ?? {});
// @ts-ignore: handler expected specific object
const result = await toolDef.handler(parsedArgs);
return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
return { content: [{ type: "text" as const, text: `Error: ${msg}` }], isError: true };
}
},
toolDef.scopes
)
);
});

// ── Compression Tools ─────────────────────────
Object.values(compressionTools).forEach((toolDef) => {
Object.values(compressionTools).forEach((toolDef: any) => {
server.registerTool(
toolDef.name,
{
description: toolDef.description,
// @ts-ignore: dynamic zod access
inputSchema: toolDef.inputSchema,
},
withScopeEnforcement(toolDef.name, async (args) => {
try {
const parsedArgs = toolDef.inputSchema.parse(args ?? {});
// @ts-expect-error - handler type lost through dynamic Object.values() access
const result = await toolDef.handler(parsedArgs);
return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
return { content: [{ type: "text" as const, text: `Error: ${msg}` }], isError: true };
}
})
withScopeEnforcement(
toolDef.name,
async (args) => {
try {
const parsedArgs = toolDef.inputSchema.parse(args ?? {});
// @ts-expect-error - handler type lost through dynamic Object.values() access
const result = await toolDef.handler(parsedArgs);
return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
return { content: [{ type: "text" as const, text: `Error: ${msg}` }], isError: true };
}
},
toolDef.scopes
)
);
});

Expand All @@ -1060,17 +1077,21 @@ export function createMcpServer(): McpServer {
// @ts-ignore: dynamic zod access
inputSchema: toolDef.inputSchema,
},
withScopeEnforcement(toolDef.name, async (args) => {
try {
const parsedArgs = toolDef.inputSchema.parse(args ?? {});
// @ts-ignore: handler expected specific object
const result = await toolDef.handler(parsedArgs);
return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
return { content: [{ type: "text" as const, text: `Error: ${msg}` }], isError: true };
}
})
withScopeEnforcement(
toolDef.name,
async (args) => {
try {
const parsedArgs = toolDef.inputSchema.parse(args ?? {});
// @ts-ignore: handler expected specific object
const result = await toolDef.handler(parsedArgs);
return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
return { content: [{ type: "text" as const, text: `Error: ${msg}` }], isError: true };
}
},
toolDef.scopes
)
);
});

Expand Down
5 changes: 5 additions & 0 deletions open-sse/mcp-server/tools/compressionTools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -299,31 +299,36 @@ export const compressionTools = {
name: "omniroute_compression_status",
description:
"Returns current compression configuration, strategy, analytics summary (requests compressed, tokens saved, avg ratio), and provider-aware cache statistics.",
scopes: ["read:compression"],
inputSchema: compressionStatusInput,
handler: (args: z.infer<typeof compressionStatusInput>) => handleCompressionStatus(args),
},
omniroute_compression_configure: {
name: "omniroute_compression_configure",
description:
"Configure compression settings at runtime. Supports enabling/disabling compression, changing strategy (off/lite/standard/aggressive/ultra/rtk/stacked), adjusting maxTokens threshold, targetRatio, auto-trigger mode, system prompt preservation, and MCP description compression.",
scopes: ["write:compression"],
inputSchema: compressionConfigureInput,
handler: (args: z.infer<typeof compressionConfigureInput>) => handleCompressionConfigure(args),
},
omniroute_set_compression_engine: {
name: "omniroute_set_compression_engine",
description: "Set the active compression engine and Caveman/RTK runtime options.",
scopes: ["write:compression"],
inputSchema: setCompressionEngineInput,
handler: (args: z.infer<typeof setCompressionEngineInput>) => handleSetCompressionEngine(args),
},
omniroute_list_compression_combos: {
name: "omniroute_list_compression_combos",
description: "List compression combos and their engine pipelines.",
scopes: ["read:compression"],
inputSchema: listCompressionCombosInput,
handler: (_args: z.infer<typeof listCompressionCombosInput>) => handleListCompressionCombos(),
},
omniroute_compression_combo_stats: {
name: "omniroute_compression_combo_stats",
description: "Get compression analytics grouped by engine and compression combo.",
scopes: ["read:compression"],
inputSchema: compressionComboStatsInput,
handler: (args: z.infer<typeof compressionComboStatsInput>) =>
handleCompressionComboStats(args),
Expand Down
8 changes: 8 additions & 0 deletions open-sse/mcp-server/tools/gamificationTools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export const gamificationTools = [
{
name: "gamification_leaderboard",
description: "Get leaderboard rankings for a scope (global, weekly, monthly, tokens_shared).",
scopes: ["read:gamification"],
inputSchema: z.object({
scope: z.enum(["global", "weekly", "monthly", "tokens_shared"]).default("global"),
limit: z.number().min(1).max(100).default(50),
Expand All @@ -23,6 +24,7 @@ export const gamificationTools = [
{
name: "gamification_rank",
description: "Get rank for an API key in a leaderboard scope.",
scopes: ["read:gamification"],
inputSchema: z.object({
apiKeyId: z.string(),
scope: z.enum(["global", "weekly", "monthly", "tokens_shared"]).default("global"),
Expand All @@ -36,6 +38,7 @@ export const gamificationTools = [
{
name: "gamification_profile",
description: "Get XP, level, and badges for an API key.",
scopes: ["read:gamification"],
inputSchema: z.object({
apiKeyId: z.string(),
}),
Expand Down Expand Up @@ -64,6 +67,7 @@ export const gamificationTools = [
{
name: "gamification_badges",
description: "List all badge definitions or earned badges for an API key.",
scopes: ["read:gamification"],
inputSchema: z.object({
apiKeyId: z.string().optional(),
category: z.string().optional(),
Expand All @@ -83,6 +87,7 @@ export const gamificationTools = [
{
name: "gamification_transfer",
description: "Transfer tokens between API keys.",
scopes: ["write:gamification"],
inputSchema: z.object({
fromApiKeyId: z.string(),
toApiKeyId: z.string(),
Expand All @@ -108,6 +113,7 @@ export const gamificationTools = [
{
name: "gamification_invite",
description: "Create an invite token for server connection.",
scopes: ["write:gamification"],
inputSchema: z.object({
apiKeyId: z.string(),
serverUrl: z.string().optional(),
Expand All @@ -122,6 +128,7 @@ export const gamificationTools = [
{
name: "gamification_servers",
description: "List connected community servers.",
scopes: ["read:gamification"],
inputSchema: z.object({}),
handler: async () => {
const { listServers } = await import("../../../src/lib/gamification/servers");
Expand All @@ -131,6 +138,7 @@ export const gamificationTools = [
{
name: "gamification_anomalies",
description: "Get flagged anomalous XP activity (admin only).",
scopes: ["read:gamification"],
inputSchema: z.object({}),
handler: async () => {
const { getAnomalies } = await import("../../../src/lib/gamification/antiCheat");
Expand Down
3 changes: 3 additions & 0 deletions open-sse/mcp-server/tools/memoryTools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export const memoryTools = {
omniroute_memory_search: {
name: "omniroute_memory_search",
description: "Search memories by query, type, or API key with token budget enforcement",
scopes: ["read:memory"],
inputSchema: MemorySearchSchema,
handler: async (args: z.infer<typeof MemorySearchSchema>) => {
const config = {
Expand Down Expand Up @@ -63,6 +64,7 @@ export const memoryTools = {
omniroute_memory_add: {
name: "omniroute_memory_add",
description: "Add a new memory entry",
scopes: ["write:memory"],
inputSchema: MemoryAddSchema,
handler: async (args: z.infer<typeof MemoryAddSchema>) => {
const memory = await createMemory({
Expand All @@ -88,6 +90,7 @@ export const memoryTools = {
omniroute_memory_clear: {
name: "omniroute_memory_clear",
description: "Clear memories for an API key, optionally filtered by type or age",
scopes: ["write:memory"],
inputSchema: MemoryClearSchema,
handler: async (args: z.infer<typeof MemoryClearSchema>) => {
const result = await listMemories({
Expand Down
Loading