Created by @_shimizu
2025年11月
しかし、AIエージェントが作った当初の仕様に重大な問題が...
// AIエージェントが実装した当初のコード
export async function getBuildings(client, args) {
const osmData = await client.query(query);
const geojson = osmToGeoJSON(osmData);
return {
content: [{
type: 'text',
text: JSON.stringify(geojson, null, 2) // 🚨 巨大データを直接返す
}]
};
}
AIエージェントの想定: 「MCPツールはAPIデータをそのまま返すもの」
→ 大容量データの場合のトークン消費を考慮していなかった
export async function getBuildings(client, args) {
const { output_path } = args;
if (output_path) {
// 🎯 ファイル保存手法: 大容量データをファイルに保存
const result = await executeGeoJSONQuery(client, query, output_path);
return {
content: [{
type: 'text',
text: JSON.stringify({
status: 'success',
message: '建物データをファイルに保存しました',
file: output_path, // ✅ ファイルパスのみ
size: result.size, // ✅ メタデータ
feature_count: result.feature_count // ✅ サマリー情報
}, null, 2)
}]
};
}
// 小さなデータは従来通り直接返却
}
大容量データ → ファイル保存
LLMには → メタデータのみ返却
export async function executeGeoJSONQuery(overpassClient, query, outputPath) {
// 1. OSMデータを一時ファイルにダウンロード
const tempPath = outputPath + '.tmp.osm.json';
await downloadToFile(server.url, fullQuery, tempPath);
// 2. OSMデータを読み込み
const osmData = JSON.parse(await fs.readFile(tempPath));
// 3. GeoJSONに変換
const geojson = osmtogeojson(osmData);
// 4. 最終ファイルに保存
await fs.writeFile(outputPath, JSON.stringify(geojson, null, 2));
// 5. 一時ファイル削除
await fs.unlink(tempPath);
return {
size: `${(Buffer.byteLength(JSON.stringify(geojson))/1024/1024).toFixed(2)} MB`,
feature_count: geojson.features.length
};
}
export async function downloadToFile(url, query, outputPath) {
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
const writeStream = createWriteStream(outputPath);
let downloadedBytes = 0;
res.on('data', (chunk) => {
downloadedBytes += chunk.length;
// 大容量ファイルの進行状況表示
if (downloadedBytes % (1024 * 1024) === 0) {
console.error(`Downloaded: ${(downloadedBytes/1024/1024).toFixed(1)} MB`);
}
});
// 🔥 ストリーミング書き込みでメモリ効率化
res.pipe(writeStream);
writeStream.on('finish', () => {
resolve({
size: `${(downloadedBytes/1024/1024).toFixed(2)} MB`,
bytes: downloadedBytes
});
});
});
req.write(query);
req.end();
});
}
AIエージェントはコードを書くことはできるが、大容量データのトークン影響は人間が指摘する必要があった
データを返すAPIを扱う場合は、最初からファイル保存手法を検討する
後から修正するよりも、設計段階で組み込む方が効率的
MCPサーバーは比較的シンプルな仕組みなのでAIエージェントがサクッとつくってくれるけど、AIは大容量データのトークンへの影響は考慮してくれないので、気づかないと不効率な実装になっていることがあるので気をつけましょう。
てか、従量課金だったら終わってた。