Skip to main content
Glama
benswel

QR for Agent

get_conversions

Retrieve QR code conversion statistics to measure ROI, analyze performance trends, and identify high-value campaigns through detailed breakdowns and daily tracking.

Instructions

Get conversion statistics for a QR code. Returns total conversions, total value, breakdowns by event name, daily trends, and recent events. Use this to measure QR code ROI and understand which codes drive the most value.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
short_idYesThe short_id of the QR code to get conversion stats for.
periodNoTime period for aggregations. Default: 30d.30d
eventNoFilter by event name (e.g., 'purchase').

Implementation Reference

  • The getConversions service function that performs the database queries to aggregate conversion data.
    export function getConversions(
      qrCodeId: number,
      shortId: string,
      period: string = "30d",
      eventFilter?: string
    ) {
      const periodStart = getPeriodStart(period);
    
      // Build conditions
      const conditions = [eq(conversionEvents.qrCodeId, qrCodeId)];
      if (periodStart) conditions.push(gt(conversionEvents.createdAt, periodStart));
      if (eventFilter) conditions.push(eq(conversionEvents.eventName, eventFilter));
    
      const whereClause = conditions.length === 1 ? conditions[0] : and(...conditions);
    
      // Total conversions
      const [{ total }] = db
        .select({ total: count() })
        .from(conversionEvents)
        .where(whereClause)
        .all();
    
      // Total value
      const [{ totalValue }] = db
        .select({ totalValue: sql<string | null>`SUM(CAST(${conversionEvents.value} AS REAL))` })
        .from(conversionEvents)
        .where(whereClause)
        .all();
    
      // By event
      const byEvent = db.all<{ event_name: string; count: number; total_value: string | null }>(
        sql`SELECT ${conversionEvents.eventName} as event_name, COUNT(*) as count,
            SUM(CAST(${conversionEvents.value} AS REAL)) as total_value
            FROM conversion_events
            WHERE ${whereClause}
            GROUP BY ${conversionEvents.eventName}
            ORDER BY count DESC`
      );
    
      // By day
      const byDay = db.all<{ date: string; count: number; total_value: string | null }>(
        sql`SELECT date(${conversionEvents.createdAt}) as date, COUNT(*) as count,
            SUM(CAST(${conversionEvents.value} AS REAL)) as total_value
            FROM conversion_events
            WHERE ${whereClause}
            GROUP BY date(${conversionEvents.createdAt})
            ORDER BY date ASC`
      );
    
      // Recent events (last 20)
      const recent = db
        .select()
        .from(conversionEvents)
        .where(whereClause)
        .orderBy(sql`${conversionEvents.createdAt} DESC`)
        .limit(20)
        .all();
    
      return {
        short_id: shortId,
        total_conversions: total,
        total_value: totalValue ? parseFloat(totalValue) : 0,
        period,
        by_event: byEvent.map((e) => ({
          event_name: e.event_name,
          count: e.count,
          total_value: e.total_value ? parseFloat(e.total_value) : 0,
        })),
        by_day: byDay.map((d) => ({
          date: d.date,
          count: d.count,
          total_value: d.total_value ? parseFloat(d.total_value) : 0,
        })),
        recent_events: recent.map((r) => ({
          event_name: r.eventName,
          value: r.value ? parseFloat(r.value) : null,
          metadata: r.metadata ? JSON.parse(r.metadata) : null,
          created_at: r.createdAt,
        })),
      };
    }
  • The API route handler that receives the request and calls the getConversions service function.
    // GET /api/conversions/:shortId — conversion stats
    app.get(
      "/:shortId",
      {
        schema: {
          ...conversionStatsSchema,
          tags: ["Conversions"],
          summary: "Get conversion statistics for a QR code",
          description:
            "Returns conversion totals, breakdowns by event name, daily trends, and recent events. Filter by period and event name.",
        },
      },
      async (request, reply) => {
        const { shortId } = request.params as { shortId: string };
        const { period = "30d", event } = request.query as {
          period?: string;
          event?: string;
        };
    
        const qr = db
          .select()
          .from(qrCodes)
          .where(
            and(
              eq(qrCodes.shortId, shortId),
              eq(qrCodes.apiKeyId, request.apiKeyId)
            )
          )
          .get();
    
        if (!qr) {
          return sendError(reply, 404, Errors.notFound("QR code", shortId));
        }
    
        return getConversions(qr.id, shortId, period, event);
      }
  • The MCP tool registration for 'get_conversions', which proxies the request to the HTTP API.
    get_conversions: {
      description:
        "Get conversion statistics for a QR code. Returns total conversions, total value, breakdowns by event name, daily trends, and recent events. Use this to measure QR code ROI and understand which codes drive the most value.",
      inputSchema: z.object({
        short_id: z.string().describe("The short_id of the QR code to get conversion stats for."),
        period: z
          .enum(["7d", "30d", "90d", "all"])
          .default("30d")
          .describe("Time period for aggregations. Default: 30d."),
        event: z
          .string()
          .optional()
          .describe("Filter by event name (e.g., 'purchase')."),
      }),
      handler: async (input: { short_id: string; period: string; event?: string }) => {
        const query: Record<string, string> = { period: input.period };
        if (input.event) query.event = input.event;
        return apiRequest(`/api/conversions/${input.short_id}`, { query });
      },
    },
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations provided, so description carries full burden. Discloses detailed return structure: 'total conversions, total value, breakdowns by event name, daily trends, and recent events.' Implies read-only behavior via 'Get' verb. Missing rate limits or cache behavior, but return transparency is strong.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two efficient sentences. First covers action and return values; second covers use case. Zero redundancy. Front-loaded with essential information. Every sentence earns its place.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

No output schema exists, but description compensates effectively by listing return fields (totals, breakdowns, trends, events). All 3 parameters documented. For a statistics retrieval tool, provides sufficient context despite missing safety annotations.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema has 100% coverage with clear descriptions for all 3 parameters. Description adds minimal semantic value beyond schema (mentions 'breakdowns by event name' which relates to the 'event' filter parameter). Baseline 3 is appropriate when schema documentation is comprehensive.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Specific verb ('Get') + resource ('conversion statistics') + scope ('for a QR code'). Clearly distinguishes from sibling 'get_qr_analytics' by focusing on conversion metrics (ROI, value) rather than general analytics, and from 'record_conversion' by being a read operation.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explicitly states use case: 'measure QR code ROI and understand which codes drive the most value.' Provides clear context for when to use. Lacks explicit 'when not to use' guidance or naming of alternative 'get_qr_analytics' for scan/view data, but implies conversion-specific usage.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/benswel/qr-agent-core'

If you have feedback or need assistance with the MCP directory API, please join our Discord server