Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
904 changes: 667 additions & 237 deletions scripts/tools.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export type { OpenAPIV3, OpenAPIV3_1 } from "openapi-types";
export { HttpClient } from "./client/http-client";
export { OpenAPIToMCPConverter } from "./openapi/parser";
export * from "./tools";
157 changes: 155 additions & 2 deletions src/mcp/__tests__/proxy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,21 @@ import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import { Headers } from "node-fetch";
import { OpenAPIV3 } from "openapi-types";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { HttpClient } from "../../client/http-client";
import { HttpClient, HttpClientError } from "../../client/http-client";
import { MCPProxy } from "../proxy";

// Mock the dependencies
vi.mock("../../client/http-client");
vi.mock("../../client/http-client", async (importOriginal) => {
const actual = await importOriginal<typeof import("../../client/http-client")>();
const MockHttpClient = vi.fn().mockImplementation(function (this: any) {
this.executeOperation = MockHttpClient.prototype.executeOperation;
});
MockHttpClient.prototype.executeOperation = vi.fn();
return {
...actual,
HttpClient: MockHttpClient,
};
});
vi.mock("@modelcontextprotocol/sdk/server/index.js");

describe("MCPProxy", () => {
Expand Down Expand Up @@ -125,6 +135,149 @@ describe("MCPProxy", () => {
content: [{ type: "text", text: JSON.stringify({ message: "success" }) }],
});
});

it("should validate and execute tool calls using ToolOverrides", async () => {
const executeMock = (HttpClient.prototype.executeOperation as ReturnType<typeof vi.fn>).mockResolvedValue(
mockSuccessResponse,
);

(proxy as any).openApiLookup = {
"API-create-object": {
operationId: "create_object",
responses: { "200": { description: "Success" } },
method: "post",
path: "/spaces/{space_id}/objects",
},
};

const [, callToolHandler] = getHandlers(proxy);
const result = await callToolHandler({
params: {
name: "API-create-object",
arguments: {
space_id: "space_123",
type_key: "page",
properties: [
{
key: "status",
format: "select",
select: "tag_1",
text: "extraneous dummy",
},
],
},
},
});

expect(result.content[0].text).toBe(JSON.stringify({ message: "success" }));
expect(executeMock).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
space_id: "space_123",
type_key: "page",
properties: [{ key: "status", format: "select", select: "tag_1" }],
}),
);
});

it("should reject invalid tool calls using ToolOverrides with structured error", async () => {
(proxy as any).openApiLookup = {
"API-create-object": {
operationId: "create_object",
responses: { "200": { description: "Success" } },
method: "post",
path: "/spaces/{space_id}/objects",
},
};

const [, callToolHandler] = getHandlers(proxy);
const result = await callToolHandler({
params: {
name: "API-create-object",
arguments: {
// Missing space_id and type_key
name: "Invalid",
},
},
});

expect(result.isError).toBe(true);
const parsed = JSON.parse(result.content[0].text);
expect(parsed.status).toBe("error");
expect(parsed.details).toBeDefined();
});

it("should validate and execute API-update-object tool calls using ToolOverrides", async () => {
const executeMock = (HttpClient.prototype.executeOperation as ReturnType<typeof vi.fn>).mockResolvedValue(
mockSuccessResponse,
);

(proxy as any).openApiLookup = {
"API-update-object": {
operationId: "update_object",
responses: { "200": { description: "Success" } },
method: "patch",
path: "/spaces/{space_id}/objects/{object_id}",
},
};

const [, callToolHandler] = getHandlers(proxy);
const result = await callToolHandler({
params: {
name: "API-update-object",
arguments: {
space_id: "space_123",
object_id: "obj_456",
name: "Updated Name",
markdown: "Updated content",
icon: null,
},
},
});

expect(result.content[0].text).toBe(JSON.stringify({ message: "success" }));
expect(executeMock).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
space_id: "space_123",
object_id: "obj_456",
name: "Updated Name",
markdown: "Updated content",
icon: null,
}),
);
});

it("should handle HttpClientError and return formatted error with isError: true", async () => {
(HttpClient.prototype.executeOperation as ReturnType<typeof vi.fn>).mockRejectedValue(
new HttpClientError("Bad Request", 400, { message: "Invalid payload from backend" }),
);

(proxy as any).openApiLookup = {
"API-create-object": {
operationId: "create_object",
responses: { "200": { description: "Success" } },
method: "post",
path: "/spaces/{space_id}/objects",
},
};

const [, callToolHandler] = getHandlers(proxy);
const result = await callToolHandler({
params: {
name: "API-create-object",
arguments: {
space_id: "space_123",
type_key: "page",
},
},
});

expect(result.isError).toBe(true);
const parsed = JSON.parse(result.content[0].text);
expect(parsed.status).toBe("error");
expect(parsed.message).toBe("Invalid payload from backend");
});
});

describe("getContentType", () => {
Expand Down
39 changes: 37 additions & 2 deletions src/mcp/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Headers } from "node-fetch";
import { OpenAPIV3 } from "openapi-types";
import { HttpClient, HttpClientError } from "../client/http-client";
import { OpenAPIToMCPConverter } from "../openapi/parser";
import { ToolOverrides } from "../tools";
import { determineBaseUrl } from "../utils/base-url";

type PathItemObject = OpenAPIV3.PathItemObject & {
Expand Down Expand Up @@ -46,7 +47,17 @@ export class MCPProxy {
const converter = new OpenAPIToMCPConverter(openApiSpec);
const { tools, openApiLookup } = converter.convertToMCPTools();
this.tools = tools;
this.openApiLookup = openApiLookup;

// Normalize openApiLookup to index both full and truncated names (<= 64 chars)
const normalizedLookup: Record<string, OpenAPIV3.OperationObject & { method: string; path: string }> = {};
for (const [key, val] of Object.entries(openApiLookup)) {
normalizedLookup[key] = val;
const truncated = this.truncateToolName(key);
if (truncated !== key) {
normalizedLookup[truncated] = val;
}
}
this.openApiLookup = normalizedLookup;

this.setupHandlers();
}
Expand Down Expand Up @@ -84,9 +95,32 @@ export class MCPProxy {
throw new Error(`Method ${name} not found`);
}

// Validate with ToolOverrides if defined
let validatedParams: Record<string, unknown> | undefined = params;
if (name in ToolOverrides) {
const parseResult = ToolOverrides[name].zodSchema.safeParse(params);
if (!parseResult.success) {
console.error("Validation error in tool call:", parseResult.error.format());
return {
content: [
{
type: "text",
text: JSON.stringify({
status: "error",
error: `Validation failed for tool '${name}'`,
details: parseResult.error.issues,
}),
},
],
isError: true,
};
}
validatedParams = parseResult.data as Record<string, unknown>;
}

try {
// Execute the operation
const response = await this.httpClient.executeOperation(operation, params);
const response = await this.httpClient.executeOperation(operation, validatedParams);

// Convert response to MCP format
return {
Expand All @@ -112,6 +146,7 @@ export class MCPProxy {
}),
},
],
isError: true,
};
}
throw error;
Expand Down
29 changes: 29 additions & 0 deletions src/openapi/__tests__/parser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1592,4 +1592,33 @@ describe("OpenAPIToMCPConverter - Additional Complex Tests", () => {
verifyTools(tools, expected.tools);
expect(openApiLookup).toEqual(expected.openApiLookup);
});

describe("ToolOverrides Integration", () => {
it("should inject ToolOverrides schema for create_object operation", () => {
const specWithCreate: OpenAPIV3.Document = {
openapi: "3.0.0",
info: { title: "Anytype API", version: "1.0.0" },
paths: {
"/v1/spaces/{space_id}/objects": {
post: {
operationId: "create_object",
summary: "Create object",
responses: { "200": { description: "Success" } },
},
},
},
};

const converter = new OpenAPIToMCPConverter(specWithCreate);
const { tools } = converter.convertToMCPTools();

expect(tools.API).toBeDefined();
const method = tools.API.methods.find((m) => m.name === "create-object");
expect(method).toBeDefined();
expect(method?.inputSchema.properties).toHaveProperty("space_id");
expect(method?.inputSchema.properties).toHaveProperty("type_key");
expect(method?.inputSchema.properties).toHaveProperty("properties");
expect(method?.inputSchema).not.toHaveProperty("$schema");
});
});
});
Loading