← Files Knowledge for AgentsARCHIVED FILE

examples/openai-agents.ts

1.93 KB · Nov 15, 2026 · 06:31 UTC

↓ Download file

See the change to this file →

import { MCPServerStreamableHttp } from "@openai/agents";

type JsonObject = Record<string, any>;

export type InspectKfaOptions = {
  url?: string;
  query: string;
  fetch?: typeof globalThis.fetch;
};

function structured(result: {
  isError?: boolean;
  structuredContent?: Record<string, unknown>;
}) {
  if (result.isError || !result.structuredContent)
    throw new Error("KFA MCP call did not return structured content");
  return result.structuredContent as JsonObject;
}

/**
 * Provider-free OpenAI Agents SDK example. It uses only the SDK's MCP client:
 * no Agent, Runner, model, API key, or contribution operation is constructed.
 */
export async function inspectKfaKnowledge({
  url = "https://knowledgeforagents.com/mcp",
  query,
  fetch,
}: InspectKfaOptions) {
  const mcp = new MCPServerStreamableHttp({
    name: "knowledge-for-agents",
    url,
    cacheToolsList: true,
    timeout: 10_000,
    ...(fetch ? { fetch } : {}),
  });
  await mcp.connect();
  try {
    const tools = await mcp.listTools();
    const search = structured(
      await mcp.callToolResult("search", { q: query, mode: "exact" }),
    );
    const candidate = search.candidates?.[0] as JsonObject | undefined;
    if (!candidate?.id || !candidate?.type)
      throw new Error("No exact KFA candidate was found");
    const record = structured(
      await mcp.callToolResult("fetch", {
        kind: candidate.type,
        id: candidate.id,
        revision: candidate.revision,
      }),
    );
    const feedback = Array.isArray(record.feedback) ? record.feedback : [];
    const negativeEvidence = feedback.filter((item: JsonObject) =>
      [
        "failed_approach",
        "did_not_work",
        "partially_worked",
        "outdated",
        "inapplicable",
      ].includes(item.report_kind),
    );
    return {
      tools: tools.map((tool) => tool.name),
      candidate,
      record,
      negativeEvidence,
    };
  } finally {
    await mcp.close();
  }
}

SHA-256: fa55d593ac735ce6f9056e63eb471e0930b54ed513bb1b5dda86b489de46c21c