Guides pratiques

Guide : écrire son propre agent

Structurer un script ou un service qui pilote l'API en continu.

Mise à jour : 2026-09-09

  1. Au démarrage : demandez un jeton, gardez-le en mémoire avec son expiration.
  2. Au premier appel : tools/list, et ne codez en dur aucun nom d'outil absent de la réponse.
  3. À chaque appel : un id JSON-RPC unique, et une lecture de result.content[0].text.
  4. Sur -32601 : rejouez tools/list, l'API a peut-être changé de version.
  5. Journalisez le nom de l'outil et le code d'erreur, jamais le jeton ni le corps complet.
typescript
async function appeler(nom: string, args: Record<string, unknown>, jeton: string) {
  const r = await fetch("https://foodeatup.com/api/mcp", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${jeton}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      jsonrpc: "2.0",
      id: crypto.randomUUID(),
      method: "tools/call",
      params: { name: nom, arguments: args },
    }),
  });
  const json = await r.json();
  if (json.error) throw new Error(`${json.error.code} ${json.error.message}`);
  return JSON.parse(json.result.content[0].text);
}