cloudflare/cloudflare-typescript

Public

mirrored fromhttps://github.com/cloudflare/cloudflare-typescriptAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v7

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

packages/mcp-server/src/instructions.ts

83lines · modecode

1// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
3import fs from 'fs/promises';
4import { getLogger } from './logger';
5import { readEnv } from './util';
6
7const INSTRUCTIONS_CACHE_TTL_MS = 15 * 60 * 1000; // 15 minutes
8
9interface InstructionsCacheEntry {
10 fetchedInstructions: string;
11 fetchedAt: number;
12}
13
14const instructionsCache = new Map<string, InstructionsCacheEntry>();
15
16export async function getInstructions({
17 stainlessApiKey,
18 customInstructionsPath,
19}: {
20 stainlessApiKey?: string | undefined;
21 customInstructionsPath?: string | undefined;
22}): Promise<string> {
23 const now = Date.now();
24 const cacheKey = customInstructionsPath ?? stainlessApiKey ?? '';
25 const cached = instructionsCache.get(cacheKey);
26
27 if (cached && now - cached.fetchedAt <= INSTRUCTIONS_CACHE_TTL_MS) {
28 return cached.fetchedInstructions;
29 }
30
31 // Evict stale entries so the cache doesn't grow unboundedly.
32 for (const [key, entry] of instructionsCache) {
33 if (now - entry.fetchedAt > INSTRUCTIONS_CACHE_TTL_MS) {
34 instructionsCache.delete(key);
35 }
36 }
37
38 let fetchedInstructions: string;
39
40 if (customInstructionsPath) {
41 fetchedInstructions = await fetchLatestInstructionsFromFile(customInstructionsPath);
42 } else {
43 fetchedInstructions = await fetchLatestInstructionsFromApi(stainlessApiKey);
44 }
45
46 instructionsCache.set(cacheKey, { fetchedInstructions, fetchedAt: now });
47 return fetchedInstructions;
48}
49
50async function fetchLatestInstructionsFromFile(path: string): Promise<string> {
51 try {
52 return await fs.readFile(path, 'utf-8');
53 } catch (error) {
54 getLogger().error({ error, path }, 'Error fetching instructions from file');
55 throw error;
56 }
57}
58
59async function fetchLatestInstructionsFromApi(stainlessApiKey: string | undefined): Promise<string> {
60 // Setting the stainless API key is optional, but may be required
61 // to authenticate requests to the Stainless API.
62 const response = await fetch(
63 readEnv('CODE_MODE_INSTRUCTIONS_URL') ?? 'https://api.stainless.com/api/ai/instructions/cloudflare',
64 {
65 method: 'GET',
66 headers: { ...(stainlessApiKey && { Authorization: stainlessApiKey }) },
67 },
68 );
69
70 let instructions: string | undefined;
71 if (!response.ok) {
72 getLogger().warn(
73 'Warning: failed to retrieve MCP server instructions. Proceeding with default instructions...',
74 );
75
76 instructions =
77 '\n This is the cloudflare MCP server.\n\n Available tools:\n - search_docs: Search SDK documentation to find the right methods and parameters.\n - execute: Run TypeScript code against a pre-authenticated SDK client. Define an async run(client) function.\n\n Workflow:\n - If unsure about the API, call search_docs first.\n - Write complete solutions in a single execute call when possible. For large datasets, use API filters to narrow results or paginate within a single execute block.\n - If execute returns an error, read the error and fix your code rather than retrying the same approach.\n - Variables do not persist between execute calls. Return or log all data you need.\n - Individual HTTP requests to the API have a 30-second timeout. If a request times out, try a smaller query or add filters.\n - Code execution has a total timeout of approximately 5 minutes. If your code times out, simplify it or break it into smaller steps.\n ';
78 }
79
80 instructions ??= ((await response.json()) as { instructions: string }).instructions;
81
82 return instructions;
83}
84