Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/mcp/src/scopes.ts
T

58 lines
1.8 KiB
TypeScript

export const MCP_WILDCARD_SCOPE = "*";
export const MCP_READ_SCOPE = "mcp:read";
export const MCP_WRITE_SCOPE = "mcp:write";
export type McpScope =
| typeof MCP_WILDCARD_SCOPE
| typeof MCP_READ_SCOPE
| typeof MCP_WRITE_SCOPE
| "mcp:lead:read"
| "mcp:lead:create"
| "mcp:contact:read"
| "mcp:project:read"
| "mcp:project:write"
| "mcp:pipeline:read"
| "mcp:activity:read"
| "mcp:activity:write"
| "mcp:task:read"
| "mcp:task:write";
export type ScopeCheck =
| { ok: true }
| {
ok: false;
status: 403;
code: "insufficient_scope";
message: string;
requiredScopes: readonly McpScope[];
};
export function normalizeMcpScopes(value: unknown): readonly McpScope[] {
if (!Array.isArray(value)) {
return [];
}
const scopes = value
.filter((scope): scope is string => typeof scope === "string")
.map((scope) => scope.trim())
.filter(Boolean);
return [...new Set(scopes)] as McpScope[];
}
export function checkMcpScopes(grantedValue: unknown, requiredScopes: readonly McpScope[]): ScopeCheck {
const granted = normalizeMcpScopes(grantedValue);
const hasWildcard = granted.includes(MCP_WILDCARD_SCOPE);
const hasDirectScope = requiredScopes.some((scope) => granted.includes(scope));
const hasReadBundle = requiredScopes.some((scope) => scope.endsWith(":read") && granted.includes(MCP_READ_SCOPE));
const hasWriteBundle = requiredScopes.some((scope) => (scope.endsWith(":write") || scope.endsWith(":create")) && granted.includes(MCP_WRITE_SCOPE));
if (hasWildcard || hasDirectScope || hasReadBundle || hasWriteBundle) {
return { ok: true };
}
return {
ok: false,
status: 403,
code: "insufficient_scope",
message: "API key scope does not allow this MCP tool.",
requiredScopes,
};
}