Skip to main content
Glama

getContractEvents

Retrieve and decode contract event logs from EVM blockchains with automatic ABI decoding, customizable block ranges, and chain support.

Instructions

컨트랙트 이벤트 로그를 조회합니다 (ABI 자동 디코딩, 최근 1000블록 기본, 블록 범위 지정 가능)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
addressYes컨트랙트 주소 (0x...)
chainNoEVM 체인ethereum
fromBlockNo시작 블록 (기본: 최근 1000블록)
limitNo최대 이벤트 수 (기본 20)

Implementation Reference

  • The main handler function that executes the logic for fetching and decoding contract logs.
    async function handler(args: z.infer<typeof inputSchema>): Promise<ToolResult<ContractEventsData>> {
      const { address, chain, limit } = args;
    
      if (!isValidAddress(address)) {
        return makeError("Invalid address format", "INVALID_INPUT");
      }
    
      const cacheKey = `events:${chain}:${address.toLowerCase()}:${args.fromBlock ?? "latest"}:${limit}`;
      const cached = cache.get<ContractEventsData>(cacheKey);
      if (cached.hit) return makeSuccess(chain, cached.data, true);
    
      try {
        const client = getClient(chain);
        const latestBlock = await client.getBlockNumber();
        const requestedFrom = args.fromBlock ? BigInt(args.fromBlock) : latestBlock - 1000n;
        const fromBlock = latestBlock - requestedFrom > BigInt(MAX_BLOCK_RANGE)
          ? latestBlock - BigInt(MAX_BLOCK_RANGE)
          : requestedFrom;
        const toBlock = latestBlock;
    
        // 로그 조회
        const logs = await client.getLogs({
          address: address as `0x${string}`,
          fromBlock,
          toBlock,
        });
    
        // ABI 조회 시도 (이벤트 디코딩용)
        let abi: Abi | null = null;
        try {
          const abiResult = await getABI(address, chain);
          if (abiResult) abi = abiResult.abi as Abi;
        } catch {
          // ABI 없으면 raw 로그 반환
        }
    
        const events: EventData[] = [];
        for (const log of logs.slice(0, limit ?? 20)) {
          let name: string | null = null;
          let decodedArgs: Record<string, unknown> | null = null;
    
          if (abi) {
            try {
              const decoded = decodeEventLog({
                abi,
                data: log.data,
                topics: log.topics,
              });
              name = decoded.eventName ?? null;
              decodedArgs = decoded.args
                ? serializeArg(decoded.args) as Record<string, unknown>
                : null;
            } catch {
              // 디코딩 실패 시 raw 유지
            }
          }
    
          events.push({
            name,
            args: decodedArgs,
            txHash: log.transactionHash ?? null,
            blockNumber: Number(log.blockNumber),
            logIndex: Number(log.logIndex),
          });
        }
    
        const result: ContractEventsData = {
          address,
          events,
          count: events.length,
          fromBlock: Number(fromBlock),
          toBlock: Number(toBlock),
        };
    
        cache.set(cacheKey, result, 30);
        return makeSuccess(chain, result, false);
      } catch (err) {
        const message = sanitizeError(err);
        return makeError(`Failed to fetch events: ${message}`, "RPC_ERROR");
      }
    }
  • Input schema definition for the getContractEvents tool using Zod.
    const inputSchema = z.object({
      address: z.string().describe("컨트랙트 주소 (0x...)"),
      chain: z.enum(SUPPORTED_CHAINS).default("ethereum").describe("EVM 체인"),
      fromBlock: z.number().optional().describe("시작 블록 (기본: 최근 1000블록)"),
      limit: z.number().optional().default(20).describe("최대 이벤트 수 (기본 20)"),
    });
  • Registration function that adds the tool to the MCP server.
    export function register(server: McpServer) {
      server.tool(
        "getContractEvents",
        "컨트랙트 이벤트 로그를 조회합니다 (ABI 자동 디코딩, 최근 1000블록 기본, 블록 범위 지정 가능)",
        inputSchema.shape,
        async (args) => {
          const result = await handler(args as z.infer<typeof inputSchema>);
          return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };
        },
      );
    }
Behavior3/5

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

With no annotations provided, the description carries the full disclosure burden. It successfully notes key behaviors (ABI auto-decoding, default recent 1000-block range, block range flexibility), but omits critical operational details like read-only safety confirmation, pagination behavior with the 'limit' parameter, or error handling when contracts are unverified.

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?

Perfectly concise Korean description structured as a single declarative sentence with high-value parenthetical details. Every clause earns its place: auto-decoding (differentiator), default range (behavioral constraint), and range flexibility (capability). No redundancy or fluff.

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

Completeness3/5

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

Adequate for basic invocation given the well-documented schema, but gaps remain due to missing output schema (no hint on decoded event structure) and missing annotations. For a blockchain query tool with 4 parameters and complex decoding logic, the description should ideally disclose output format or caching behavior.

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?

Input schema has 100% description coverage, establishing a baseline of 3. The description adds high-level context about the 1000-block default window which clarifies fromBlock's implied scope, but does not augment parameter syntax, formats, or interdependencies (e.g., how limit interacts with block range) beyond what the schema already documents.

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

Purpose4/5

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

The description uses a specific verb ('조회합니다' / retrieve) and resource ('컨트랙트 이벤트 로그'), and distinguishes itself from siblings like decodeTx or getTokenTransfers by highlighting 'ABI 자동 디코딩' (auto-decoding), implying it handles the full pipeline from raw logs to decoded events.

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

Usage Guidelines3/5

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

Provides implicit usage guidance through parenthetical constraints (default 1000-block window, block range capability), helping agents understand the query window behavior. However, it lacks explicit guidance on when to use this versus alternatives like decodeTx or getContractABI, and does not mention prerequisites (e.g., contract verification for decoding).

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/calintzy/evmscope'

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