ad4agentBuilt on ad4mat / advanced store

Build a shopping agent with Vercel eve and ad4agent

Step by step: build an eve agent that recommends shops through the ad4agent MCP server and earns commission on confirmed sales. Full code included.

Published 12 min read
  • eve
  • MCP
  • Shopping agent
  • Monetization

Shopping agents are good at turning a vague request (“a waterproof running jacket, shipped in Germany”) into a short list of shops. What they usually can’t do is earn anything when that recommendation becomes a purchase. This guide shows how to build a shopping agent with eve, Vercel’s framework for durable backend agents, and connect it to ad4agent so the links it shares are attributed to your account.

You will end up with a working agent of five small files. All code on this page is taken from that example, and it uses only documented eve APIs (eve 1.1).

The problem

Affiliate marketing pays for recommendations, but it was built for websites. Each network has its own sign-up, approval, link format and reporting. For an agent that might recommend any shop in any country, wiring up networks one by one does not scale, and a model should never be trusted to build tracking links by itself.

ad4agent solves this with one integration: your agent asks for shops or hands over a merchant URL, and gets back links attributed to your account where a program exists. Today the integration is a remote MCP server; a REST API, SDK and CLI are coming soon. Tracking and payouts run through ad4mat by advanced store.

Architecture

  1. The user asks your eve agent for a product or a shop.
  2. The agent finds the ad4agent connection and calls search_tracking_links (shops by keyword, category and country) or get_tracking_link (one merchant URL).
  3. eve sends the call to https://ad4agent.com/mcp with your OAuth access token. The model never sees the token.
  4. ad4agent returns the shop, a tracking_link and fields that say whether the link is ready and whether tracking is expected.
  5. The agent answers with a labeled affiliate link, or the normal shop link when tracking is not confirmed.
  6. When the shopper buys and the merchant confirms the sale, the commission is credited to your account.

In eve terms, the agent is a directory: agent/instructions.md holds the behavior, agent/connections/ad4agent.ts holds the MCP connection, and a small helper in agent/lib/ supplies the token.

project layout
shopping-agent/
├── agent/
│   ├── agent.ts                 # model config (from eve init)
│   ├── instructions.md          # shopping behavior
│   ├── channels/eve.ts          # HTTP channel (from eve init)
│   ├── connections/ad4agent.ts  # ad4agent MCP connection
│   └── lib/ad4agent-token.ts    # token store with refresh
├── scripts/ad4agent-login.mjs   # one-time OAuth sign-in
└── package.json

Prerequisites

  • Node.js 24 or newer.
  • Model access: an AI Gateway, OpenAI or Anthropic API key, or a ChatGPT subscription for local use. eve’s /login in the terminal UI walks you through it.
  • An ad4agent account. Sign up with your email; it takes a minute.
  • For payouts: a verified account owner. You can build and test without it, but tracked links are only issued after verification (see How you get paid).

1. Create the eve project

terminalbash
npx eve@latest init shopping-agent
cd shopping-agent

This scaffolds the project, installs eve, ai and zod, and creates agent/agent.ts with a default model. You can keep it as is or change the model later with /model:

agent/agent.tsts
import { defineAgent } from "eve";

export default defineAgent({
  model: "openai/gpt-6-luna-fast",
  reasoning: "high",
});

2. Write the instructions

Replace agent/instructions.md. The rules matter more than the wording: rank by relevance rather than commission, disclose affiliate links, and only present a link as an affiliate link when ad4agent says it is ready and tracking is expected.

agent/instructions.mdmarkdown
# Identity

You are a shopping assistant. You help people find online shops and products that fit what they ask for.

# How to work

- Use the `ad4agent` connection to find shops: `search_tracking_links` for shop or category searches (short English keywords, ISO country code such as `DE`), `get_tracking_link` when the user gives you a specific merchant URL.
- Recommend by relevance to the user, never by commission. Suggest at most five shops, with one sentence each on why they fit.
- ad4agent has no prices, stock or shipping data. Say so when it matters, and tell the user to check on the merchant's site.

# Links

- Use a returned `tracking_link` as an affiliate link only when `link_status` is `ready` and `tracked_expected` is not `false`. Add a short note such as "Affiliate link: we may earn a commission."
- If `tracked_expected` is `false`, or no link is ready, link the shop's normal `website` instead and do not call it an affiliate link.
- If the user asks for no affiliate links, use the normal `website` only.
- Never invent, shorten or rewrite links. Never open or click them yourself.
- If a result has `reason: "OWNER_NOT_VERIFIED"`, recommend shops with their normal website and mention that the account owner still needs to finish verification on ad4agent.

3. Add a token provider

The ad4agent MCP server uses OAuth 2.1. Access tokens are valid for one hour; refresh tokens rotate on every use and the grant lasts 30 days. eve’s connection auth.getToken can return any token plus an expiresAt, and calls it again when that time passes. This helper reads the tokens saved by the sign-in script, refreshes them when needed and writes the newest refresh token back:

agent/lib/ad4agent-token.tsts
import type { TokenResult } from "eve/connections";

/**
 * Minimal token store for one ad4agent account.
 *
 * `npm run login` writes `.ad4agent/tokens.json` after you approve access in the
 * browser. This module returns a valid access token and refreshes it when it
 * expires. ad4agent rotates refresh tokens, so the newest one is written back.
 *
 * For a deployment, replace the file with a durable secret store (KV, database).
 */
export const AD4AGENT_ORIGIN = process.env.AD4AGENT_ORIGIN ?? "https://ad4agent.com";

type StoredTokens = {
  client_id: string;
  access_token: string;
  refresh_token?: string;
  expires_at: number; // ms since epoch
};

async function tokenFile() {
  const { resolve } = await import("node:path");
  return resolve(process.env.AD4AGENT_TOKEN_FILE ?? ".ad4agent/tokens.json");
}

async function readTokens(): Promise<StoredTokens> {
  const { readFile } = await import("node:fs/promises");
  try {
    return JSON.parse(await readFile(await tokenFile(), "utf8")) as StoredTokens;
  } catch {
    throw new Error("No ad4agent tokens found. Run `npm run login` first.");
  }
}

async function writeTokens(tokens: StoredTokens) {
  const { mkdir, writeFile } = await import("node:fs/promises");
  const { dirname } = await import("node:path");
  const file = await tokenFile();
  await mkdir(dirname(file), { recursive: true });
  await writeFile(file, JSON.stringify(tokens, null, 2), { mode: 0o600 });
}

async function refresh(tokens: StoredTokens): Promise<StoredTokens> {
  if (!tokens.refresh_token) {
    throw new Error("ad4agent access token expired. Run `npm run login` again.");
  }
  const res = await fetch(`${AD4AGENT_ORIGIN}/oauth/token`, {
    method: "POST",
    headers: { "content-type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      grant_type: "refresh_token",
      refresh_token: tokens.refresh_token,
      client_id: tokens.client_id,
    }),
  });
  if (!res.ok) {
    // invalid_grant: the grant was revoked or is older than 30 days.
    throw new Error(`ad4agent token refresh failed (${res.status}). Run \`npm run login\` again.`);
  }
  const body = (await res.json()) as { access_token: string; refresh_token?: string; expires_in: number };
  const next: StoredTokens = {
    client_id: tokens.client_id,
    access_token: body.access_token,
    refresh_token: body.refresh_token ?? tokens.refresh_token,
    expires_at: Date.now() + body.expires_in * 1000,
  };
  await writeTokens(next);
  return next;
}

/** Token provider for the ad4agent MCP connection. */
export async function getAd4agentToken(): Promise<TokenResult> {
  let tokens = await readTokens();
  // Refresh one minute early so a call never starts with an expiring token.
  if (tokens.expires_at - 60_000 <= Date.now()) tokens = await refresh(tokens);
  return { token: tokens.access_token, expiresAt: tokens.expires_at - 60_000 };
}

4. Connect the ad4agent MCP server

An eve connection is one file in agent/connections/; the filename becomes the connection name. principalType: "app" means every conversation uses your ad4agent account, which is what you want when the agent should earn for you. The allow list keeps the surface to the three shopping tools.

agent/connections/ad4agent.tsts
import { defineMcpClientConnection } from "eve/connections";
import { AD4AGENT_ORIGIN, getAd4agentToken } from "../lib/ad4agent-token";

// The filename is the connection name: tools appear as ad4agent__<tool>.
export default defineMcpClientConnection({
  url: `${AD4AGENT_ORIGIN}/mcp`,
  description:
    "ad4agent: find online shops by name, category and country, and turn merchant URLs into affiliate links for the connected account. No prices or stock.",
  auth: {
    principalType: "app", // one ad4agent account (yours) for every session
    getToken: getAd4agentToken,
  },
  // Only the shopping tools. Account sign-up stays on the website.
  tools: { allow: ["search_tracking_links", "get_tracking_link", "list_categories"] },
});

The model discovers the tools through eve’s built-in search and calls them as ad4agent__search_tracking_links, ad4agent__get_tracking_link and ad4agent__list_categories. See the MCP docs for every parameter and result field.

5. Sign in once

The sign-in script registers a local OAuth client, opens the ad4agent consent page and stores the tokens in .ad4agent/tokens.json. It uses the standard flow the server advertises at /.well-known/oauth-authorization-server: dynamic client registration, authorization code with PKCE (S256) and the scopes affiliate:read and offline_access.

scripts/ad4agent-login.mjsjs
// One-time sign-in: registers a local OAuth client with ad4agent, opens the
// consent page in your browser and stores the tokens in .ad4agent/tokens.json.
// OAuth 2.1 authorization code flow with PKCE (S256) and dynamic client registration.
import { createHash, randomBytes } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import { createServer } from "node:http";
import { dirname, resolve } from "node:path";

const ORIGIN = process.env.AD4AGENT_ORIGIN ?? "https://ad4agent.com";
const PORT = Number(process.env.AD4AGENT_LOGIN_PORT ?? 8976);
const REDIRECT_URI = `http://127.0.0.1:${PORT}/callback`;
const TOKEN_FILE = resolve(process.env.AD4AGENT_TOKEN_FILE ?? ".ad4agent/tokens.json");
const b64url = (buf) => buf.toString("base64url");

// 1. Register a public client (no secret) for this machine.
const reg = await fetch(`${ORIGIN}/oauth/register`, {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify({
    client_name: "eve shopping agent (local)",
    redirect_uris: [REDIRECT_URI],
    grant_types: ["authorization_code", "refresh_token"],
    response_types: ["code"],
    token_endpoint_auth_method: "none",
  }),
});
if (!reg.ok) throw new Error(`Client registration failed: ${reg.status} ${await reg.text()}`);
const { client_id } = await reg.json();

// 2. Build the authorization URL with PKCE.
const verifier = b64url(randomBytes(32));
const challenge = b64url(createHash("sha256").update(verifier).digest());
const state = b64url(randomBytes(16));
const authorize = new URL(`${ORIGIN}/authorize`);
authorize.search = new URLSearchParams({
  response_type: "code",
  client_id,
  redirect_uri: REDIRECT_URI,
  scope: "affiliate:read offline_access",
  state,
  code_challenge: challenge,
  code_challenge_method: "S256",
  resource: `${ORIGIN}/mcp`,
}).toString();

// 3. Wait for the redirect, then exchange the code for tokens.
const code = await new Promise((resolveCode, reject) => {
  const server = createServer((req, res) => {
    const url = new URL(req.url ?? "/", REDIRECT_URI);
    if (url.pathname !== "/callback") return void res.writeHead(404).end();
    const ok = url.searchParams.get("state") === state && url.searchParams.get("code");
    res.writeHead(ok ? 200 : 400, { "content-type": "text/plain" });
    res.end(ok ? "ad4agent connected. You can close this tab." : "Sign-in failed. Check the terminal.");
    server.close();
    ok ? resolveCode(url.searchParams.get("code")) : reject(new Error(url.searchParams.get("error") ?? "state mismatch"));
  });
  server.listen(PORT, "127.0.0.1", () => {
    console.log(`Open this URL, sign in to ad4agent and approve access:\n\n${authorize}\n`);
  });
});

const res = await fetch(`${ORIGIN}/oauth/token`, {
  method: "POST",
  headers: { "content-type": "application/x-www-form-urlencoded" },
  body: new URLSearchParams({
    grant_type: "authorization_code",
    code,
    redirect_uri: REDIRECT_URI,
    client_id,
    code_verifier: verifier,
    resource: `${ORIGIN}/mcp`,
  }),
});
if (!res.ok) throw new Error(`Token exchange failed: ${res.status} ${await res.text()}`);
const t = await res.json();

await mkdir(dirname(TOKEN_FILE), { recursive: true });
await writeFile(
  TOKEN_FILE,
  JSON.stringify(
    { client_id, access_token: t.access_token, refresh_token: t.refresh_token, expires_at: Date.now() + t.expires_in * 1000 },
    null,
    2,
  ),
  { mode: 0o600 },
);
console.log(`Saved tokens to ${TOKEN_FILE}. Start the agent with: npm run dev`);

Add the script and keep the token file out of Git and out of deployments:

terminalbash
npm pkg set scripts.login="node scripts/ad4agent-login.mjs"
echo ".ad4agent" >> .gitignore
echo ".ad4agent" >> .vercelignore
npm run login

6. Run and test

terminalbash
npm run dev

The eve terminal UI opens. Try “Find a running shop in Germany” or “Make this an affiliate link: https://www.example-shop.de/”. For a URL, the agent calls get_tracking_link and gets a result like this (shortened):

get_tracking_link resultjson
{
  "status": "ready",
  "url": "https://www.example-shop.de/",
  "shop": { "name": "Example Shop", "domain": "example-shop.de", "website": "https://www.example-shop.de/" },
  "tracking_link": "https://…",
  "link_status": "ready",
  "link_scope": "target",
  "tracked_expected": true,
  "link_message": "Your personal affiliate link is ready.",
  "disclosure": "Tell the user this is an affiliate link."
}

Three fields drive what the agent says:

  • tracked_expected: false means the link works but the shop is not confirmed for tracking. The instructions tell the agent to use the normal shop link then.
  • link_scope: homepage means the program only tracks its homepage, so the link opens the shop’s start page rather than the product.
  • reason and link_message: why no link is available, for example OWNER_NOT_VERIFIED before your owner verification is approved.

To test over HTTP instead of the terminal UI, start npx eve dev --no-ui and send a message with POST /eve/v1/session; the eve docs describe the session and stream routes.

Deploying

  • Tokens: a serverless deployment has no writable, persistent file system. Replace the file in ad4agent-token.ts with a durable secret store such as a KV store or database, and always save the rotated refresh token.
  • Re-consent: the grant expires 30 days after sign-in. Run the sign-in again before then; the token provider throws a clear error when it can’t refresh.
  • Channel auth: the scaffolded agent/channels/eve.ts blocks browser requests in production until you add your own auth. Configure it before you expose the agent.
  • Per-user accounts: if each of your users should earn with their own ad4agent account, switch to user-scoped auth: eve’s defineInteractiveAuthorization lets you run this OAuth flow for each user and pauses the turn until they have signed in.

eve deploy links a Vercel project and deploys the agent; see eve’s deployment guide for environment variables and protection settings.

How you get paid

ad4agent pays commission on purchases your agent’s links lead to. A few conditions decide whether a click becomes money:

  • Verified owner. Payouts need a one-time owner verification on the website. Until it is approved, the tools return reason: "OWNER_NOT_VERIFIED" and no tracked link, and your agent recommends shops with their normal URL.
  • Tracking confirmed. Only links with tracked_expected not false are expected to be attributed.
  • Confirmed sales only. The merchant confirms each sale after its return and validation period. That can take up to six months. Cancelled and returned orders are not paid.
  • Estimates are estimates. avg_commission in search results is an estimated average for your account, not a guaranteed amount per purchase.

Disclose affiliate links to your users (our affiliate disclosure shows how) and respect a request not to use them. Ranking by relevance rather than commission keeps the agent useful, which is what makes people come back to it.

FAQ

Do I need an account with each affiliate network?

No. ad4agent bundles merchant programs from 103 affiliate networks behind one integration. You need one ad4agent account, and for payouts a verified account owner.

Does ad4agent return product prices or stock?

No. ad4agent returns merchant programs and links, not a product catalog. Your agent should check prices, stock and shipping on the merchant’s site or with another tool.

What does tracked_expected: false mean?

The link works, but the shop is not confirmed for tracking, so the click may not be attributed. Present it as a normal shop link and do not promise a commission.

When do I get paid?

Only for sales the merchant confirms. Confirmation can take up to six months, depending on the merchant’s return and validation period. Cancelled or returned orders are not paid.

Does the shopper pay more through an affiliate link?

No. The shopper pays the merchant’s normal price. The commission is paid by the merchant.

Can I use something other than eve?

Yes. Any MCP client can connect to the same endpoint, for example Claude, ChatGPT or your own agent. A REST API, SDK and CLI are coming soon.

Do I have to deploy to Vercel?

No. eve runs locally with npm run dev and can be self-hosted. eve deploy is the shortest path to Vercel if you want it.

Connect your agent

Create an account, finish owner verification, and point your agent at https://ad4agent.com/mcp.