今朝OpenAI Agents SDKのJavaScript版が登場したので、早速使ってみました。
以前Python版で同じことをしてみたときの記事↓
環境
- Debian: 12.11 (ChromeOS Linux開発環境)
- mise: 2025.4.5 linux-x64
- node: v24.1.0
- @openai/agents: 0.0.1
実装
適当に環境構築します。
$ mise use node
$ npm init -y
$ npm install @openai/agents
.env
にOPENAI_API_KEY
を入れておきます。
まずMCP無しの挙動を確認します。LLMに「いま何時?」と聞いてみますが、そのままでは答えてくれません。
index.js
import { Agent, run } from '@openai/agents';
const agent = new Agent({
name: 'アシスタント',
instructions: 'あなたは優秀なアシスタントです',
model: 'gpt-4.1-mini'
});
const result = await run(agent, 'いま何時?');
console.log(result.finalOutput);
$ node index.js
ごめんなさい、現在の時刻を確認することはできません。お使いのデバイスで時間を確認してください。
関数ツールによる実装
MCPを使わず、OpenAI Agents SDKの関数ツールを使ってみます。現在時刻を取得するgetTimeTool
を実装して、同じく「いま何時?」を実行してみます。
index.js
import { Agent, run, tool } from '@openai/agents';
const getTimeTool = tool({
name: 'get_time',
description: '現在時刻を調べる',
parameters: {
type: 'object',
properties: {},
required: [],
additionalProperties: false,
},
async execute(_input) {
return new Date();
},
});
const agent = new Agent({
name: 'アシスタント',
instructions: 'あなたは優秀なアシスタントです',
model: 'gpt-4.1-mini',
tools: [getTimeTool]
});
const result = await run(agent, 'いま何時?');
console.log(result.finalOutput);
$ node index.js
現在の時刻は日本時間で2025年6月4日午後10時11分頃です。何か他に知りたいことはありますか?
うまく行きました。とてもシンプルな実装でツール呼び出しを実現できました。
MCPを使う場合
同じことをMCPでも実装してみます。$ npm install @modelcontextprotocol/sdk
で、MCPのSDKをインストールし、現在時刻を取得するMCP Serverをwhattime.js
に定義します。
whattime.js
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
const server = new McpServer({
name: "WhatTime",
version: "1.0.0"
});
// 現在時刻を取得する関数
server.tool("whattime",
{},
async ({}) => ({
content: [{ type: "text", text: new Date() }]
})
);
const transport = new StdioServerTransport();
await server.connect(transport);
このMCP Serverを呼び出すコードを書きます。
index.js
import { Agent, run, tool } from '@openai/agents';
import { MCPServerStdio } from '@openai/agents-core/_shims';
const mcpServer = await new MCPServerStdio({
"command": "node",
"args": ["whattime.js"],
});
await mcpServer.connect();
const agent = new Agent({
name: 'アシスタント',
instructions: 'あなたは優秀なアシスタントです',
model: 'gpt-4.1-mini',
mcpServers: [mcpServer]
});
const result = await run(agent, 'いま何時?');
console.log(result.finalOutput);
$ node index.js
現在の時刻は2025年6月4日 13時26分(UTC)です。日本時間など他のタイムゾーンの時刻が知りたい場合は教えてください。
無事、JavaScript版OpenAI Agents SDKでもMCPをつかう事ができました。