Skip to content

Commit b84651e

Browse files
committed
Minor changes, add clientSse.ts
1 parent ca69a88 commit b84651e

File tree

4 files changed

+109
-8
lines changed

4 files changed

+109
-8
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,3 +310,4 @@ Upon launching, the Inspector will display a URL that you can access in your bro
310310
- Provide tools to search for Actors and load them as needed.
311311
- Add Apify's dataset and key-value store as resources.
312312
- Add tools such as Actor logs and Actor runs for debugging.
313+
- Prune Actors input schema to reduce context size.

src/const.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,9 @@ export const defaults = {
99
],
1010
};
1111

12-
export const ACTOR_OUTPUT_MAX_CHARS_PER_ITEM = 1_000;
12+
export const ACTOR_OUTPUT_MAX_CHARS_PER_ITEM = 2_000;
1313
export const ACTOR_OUTPUT_TRUNCATED_MESSAGE = `Output was truncated because it will not fit into context.`
14-
+ `There is no reason to call this tool again!`;
14+
+ ` There is no reason to call this tool again!`;
1515

1616
export enum Routes {
1717
ROOT = '/',

src/examples/clientSse.ts

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
/* eslint-disable no-console */
2+
/**
3+
* Connect to the MCP server using SSE transport and call a tool.
4+
* The Actors MCP Server will load default Actors.
5+
*
6+
* !!! This example needs to be fixed as it does not work !!!
7+
*/
8+
9+
import path from 'path';
10+
import { fileURLToPath } from 'url';
11+
12+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
13+
import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
14+
import { CallToolResultSchema } from '@modelcontextprotocol/sdk/types.js';
15+
import dotenv from 'dotenv';
16+
import { EventSource } from 'eventsource';
17+
18+
// Resolve dirname equivalent in ES module
19+
const filename = fileURLToPath(import.meta.url);
20+
const dirname = path.dirname(filename);
21+
22+
dotenv.config({ path: path.resolve(dirname, '../../.env') });
23+
24+
const SERVER_URL = 'https://actors-mcp-server/sse';
25+
// We need to change forward slash / to underscore _ in the tool name as Anthropic does not allow forward slashes in the tool name
26+
const SELECTED_TOOL = 'apify_rag-web-browser';
27+
28+
if (!process.env.APIFY_TOKEN) {
29+
console.error('APIFY_TOKEN is required but not set in the environment variables.');
30+
process.exit(1);
31+
}
32+
33+
if (typeof globalThis.EventSource === 'undefined') {
34+
globalThis.EventSource = EventSource as unknown as typeof globalThis.EventSource;
35+
}
36+
37+
async function main(): Promise<void> {
38+
const transport = new SSEClientTransport(
39+
new URL(SERVER_URL),
40+
{
41+
requestInit: {
42+
headers: {
43+
authorization: `Bearer ${process.env.APIFY_TOKEN}`,
44+
},
45+
},
46+
eventSourceInit: {
47+
// The EventSource package augments EventSourceInit with a "fetch" parameter.
48+
// You can use this to set additional headers on the outgoing request.
49+
// Based on this example: https://github.com/modelcontextprotocol/typescript-sdk/issues/118
50+
async fetch(input: Request | URL | string, init?: RequestInit) {
51+
const headers = new Headers(init?.headers || {});
52+
headers.set('authorization', `Bearer ${process.env.APIFY_TOKEN}`);
53+
return fetch(input, { ...init, headers });
54+
},
55+
// We have to cast to "any" to use it, since it's non-standard
56+
} as any, // eslint-disable-line @typescript-eslint/no-explicit-any
57+
},
58+
);
59+
const client = new Client(
60+
{ name: 'example-client', version: '1.0.0' },
61+
{ capabilities: {} },
62+
);
63+
64+
try {
65+
// Connect to the MCP server
66+
await client.connect(transport);
67+
68+
// List available tools
69+
const tools = await client.listTools();
70+
console.log('Available tools:', tools);
71+
72+
if (tools.tools.length === 0) {
73+
console.log('No tools available');
74+
return;
75+
}
76+
77+
const selectedTool = tools.tools.find((tool) => tool.name === SELECTED_TOOL);
78+
if (!selectedTool) {
79+
console.error(`The specified tool: ${selectedTool} is not available. Exiting.`);
80+
return;
81+
}
82+
83+
// Call a tool
84+
console.log('Calling actor ...');
85+
const result = await client.callTool(
86+
{ name: SELECTED_TOOL, arguments: { query: 'web browser for Anthropic' } },
87+
CallToolResultSchema,
88+
);
89+
console.log('Tool result:', JSON.stringify(result, null, 2));
90+
} catch (error: unknown) {
91+
if (error instanceof Error) {
92+
console.error('Error:', error.message);
93+
console.error(error.stack);
94+
} else {
95+
console.error('An unknown error occurred:', error);
96+
}
97+
}
98+
}
99+
100+
await main();

src/examples/client_sse.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,23 +9,23 @@
99

1010
import asyncio
1111
import os
12+
from pathlib import Path
1213

1314
import requests
1415
from dotenv import load_dotenv
1516
from mcp.client.session import ClientSession
1617
from mcp.client.sse import sse_client
1718

18-
load_dotenv(dotenv_path="../../.env")
19+
load_dotenv(Path(__file__).resolve().parent.parent.parent / ".env")
1920

20-
MCP_SERVER_URL = "https://mcp-server.apify.actor"
21-
ACTORS = "apify/rag-web-browser"
21+
MCP_SERVER_URL = "https://actors-mcp-server.apify.actor"
2222

2323
HEADERS = {"Authorization": f"Bearer {os.getenv('APIFY_TOKEN')}"}
2424

2525
async def run() -> None:
2626

27-
print("Start MCP Server with Actors", ACTORS)
28-
r = requests.get(MCP_SERVER_URL, params={"actors": ACTORS}, headers=HEADERS)
27+
print("Start MCP Server with Actors",)
28+
r = requests.get(MCP_SERVER_URL, headers=HEADERS)
2929
print("MCP Server Response:", r.json(), end="\n\n")
3030

3131
async with sse_client(url=f"{MCP_SERVER_URL}/sse", timeout=60, headers=HEADERS) as (read, write):
@@ -36,7 +36,7 @@ async def run() -> None:
3636
print("Available Tools:", tools, end="\n\n")
3737

3838
if hasattr(tools, "tools") and not tools.tools:
39-
print("No tools available! Start MCP server with Actors")
39+
print("No tools available!")
4040
return
4141

4242
result = await session.call_tool("apify/rag-web-browser", { "query": "example.com", "maxResults": 3 })

0 commit comments

Comments
 (0)