Skip to main content
Glama

contract_get_function_args

Parse a contract's ABI or use nearblocks.io API to retrieve function call arguments for NEAR blockchain. Checks recent method executions to identify likely inputs. Experimental tool.

Instructions

Get the arguments of a function call by parsing the contract's ABI or by using the nearblocks.io API (as a fallback). This function API checks recent execution results of the contract's method being queried to determine the likely arguments of the function call. Warning: This tool is experimental and is not garunteed to get the correct arguments.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
contractIdYes
methodNameYes
networkIdNomainnet

Implementation Reference

  • Registration of the 'contract_get_function_args' MCP tool, including name, description, input schema, and handler function.
    mcp.tool(
      'contract_get_function_args',
      noLeadingWhitespace`
      Get the arguments of a function call by parsing the contract's ABI or by using the nearblocks.io API (as a fallback).
      This function API checks recent execution results of the contract's method being queried
      to determine the likely arguments of the function call.
      Warning: This tool is experimental and is not garunteed to get the correct arguments.`,
      {
        contractId: z.string(),
        methodName: z.string(),
        networkId: z.enum(['testnet', 'mainnet']).default('mainnet'),
      },
      async (args, _) => {
        const connection = await connect({
          networkId: args.networkId,
          nodeUrl: getEndpointsByNetwork(args.networkId)[0]!,
        });
        const contractAccountResult: Result<Account, Error> = await getAccount(
          args.contractId,
          connection,
        );
        if (!contractAccountResult.ok) {
          return {
            content: [
              { type: 'text', text: `Error: ${contractAccountResult.error}` },
            ],
          };
        }
    
        const contractMethods = await getContractMethods(
          args.contractId,
          connection,
        );
        if (!contractMethods.ok) {
          return {
            content: [
              {
                type: 'text',
                text: `Error: ${contractMethods.error}`,
              },
            ],
          };
        }
        if (contractMethods.value.length === 0) {
          return {
            content: [
              {
                type: 'text',
                text: `No methods found for contract ${args.contractId}`,
              },
            ],
          };
        }
        if (!contractMethods.value.includes(args.methodName)) {
          return {
            content: [
              {
                type: 'text',
                text: `Method ${args.methodName} not found for contract ${args.contractId}`,
              },
            ],
          };
        }
    
        const parsedContractABIResult = await getContractABI(
          contractAccountResult.value,
          args.contractId,
        );
    
        // if the contract ABI is not found, ignore, only return if
        // the contract ABI is found
        if (parsedContractABIResult.ok) {
          const abi = parsedContractABIResult.value;
          const method = abi.body.functions.find(
            (method) => method.name === args.methodName,
          );
          if (!method) {
            return {
              content: [
                {
                  type: 'text',
                  text: `Method ${args.methodName} not found in contract ${args.contractId}`,
                },
              ],
            };
          }
          return {
            content: [
              {
                type: 'text',
                text: stringify_bigint({
                  ...method,
                  args: method.params?.args || {},
                }),
              },
            ],
          };
        }
    
        // TODO: This function uses near blocks api which is rate limited
        //       and will fail if we call it too many times. We should
        //       use another method to get the contract methods.
        const parsedContractMethodsResult: Result<JsonSchema7Type, Error> =
          await (async () => {
            try {
              const parsedMethod = await getParsedContractMethod(
                args.contractId,
                args.methodName,
              );
              if (!parsedMethod.ok) {
                return parsedMethod;
              }
              const zodArgsResult = json_to_zod(
                parsedMethod.value.action.length > 0
                  ? parsedMethod.value.action[0]?.args.args_json
                  : {},
              );
              if (!zodArgsResult.ok) {
                return zodArgsResult;
              }
              const jsonSchema = zodToJsonSchema(zodArgsResult.value);
              return {
                ok: true,
                value: jsonSchema,
              };
            } catch (e) {
              return { ok: false, error: new Error(e as string) };
            }
          })();
        if (!parsedContractMethodsResult.ok) {
          return {
            content: [
              {
                type: 'text',
                text: `Error Parsing Contract Methods: ${parsedContractMethodsResult.error}`,
              },
            ],
          };
        }
        const parsedContractMethods = parsedContractMethodsResult.value;
    
        return {
          content: [
            {
              type: 'text',
              text: stringify_bigint(parsedContractMethods),
            },
          ],
        };
      },
    );
  • The main handler function for the tool. Connects to NEAR, validates contract account and method existence, attempts to fetch ABI via __contract_abi for params, falls back to parsing recent tx args from nearblocks.io API using getParsedContractMethod and json_to_zod.
    async (args, _) => {
      const connection = await connect({
        networkId: args.networkId,
        nodeUrl: getEndpointsByNetwork(args.networkId)[0]!,
      });
      const contractAccountResult: Result<Account, Error> = await getAccount(
        args.contractId,
        connection,
      );
      if (!contractAccountResult.ok) {
        return {
          content: [
            { type: 'text', text: `Error: ${contractAccountResult.error}` },
          ],
        };
      }
    
      const contractMethods = await getContractMethods(
        args.contractId,
        connection,
      );
      if (!contractMethods.ok) {
        return {
          content: [
            {
              type: 'text',
              text: `Error: ${contractMethods.error}`,
            },
          ],
        };
      }
      if (contractMethods.value.length === 0) {
        return {
          content: [
            {
              type: 'text',
              text: `No methods found for contract ${args.contractId}`,
            },
          ],
        };
      }
      if (!contractMethods.value.includes(args.methodName)) {
        return {
          content: [
            {
              type: 'text',
              text: `Method ${args.methodName} not found for contract ${args.contractId}`,
            },
          ],
        };
      }
    
      const parsedContractABIResult = await getContractABI(
        contractAccountResult.value,
        args.contractId,
      );
    
      // if the contract ABI is not found, ignore, only return if
      // the contract ABI is found
      if (parsedContractABIResult.ok) {
        const abi = parsedContractABIResult.value;
        const method = abi.body.functions.find(
          (method) => method.name === args.methodName,
        );
        if (!method) {
          return {
            content: [
              {
                type: 'text',
                text: `Method ${args.methodName} not found in contract ${args.contractId}`,
              },
            ],
          };
        }
        return {
          content: [
            {
              type: 'text',
              text: stringify_bigint({
                ...method,
                args: method.params?.args || {},
              }),
            },
          ],
        };
      }
    
      // TODO: This function uses near blocks api which is rate limited
      //       and will fail if we call it too many times. We should
      //       use another method to get the contract methods.
      const parsedContractMethodsResult: Result<JsonSchema7Type, Error> =
        await (async () => {
          try {
            const parsedMethod = await getParsedContractMethod(
              args.contractId,
              args.methodName,
            );
            if (!parsedMethod.ok) {
              return parsedMethod;
            }
            const zodArgsResult = json_to_zod(
              parsedMethod.value.action.length > 0
                ? parsedMethod.value.action[0]?.args.args_json
                : {},
            );
            if (!zodArgsResult.ok) {
              return zodArgsResult;
            }
            const jsonSchema = zodToJsonSchema(zodArgsResult.value);
            return {
              ok: true,
              value: jsonSchema,
            };
          } catch (e) {
            return { ok: false, error: new Error(e as string) };
          }
        })();
      if (!parsedContractMethodsResult.ok) {
        return {
          content: [
            {
              type: 'text',
              text: `Error Parsing Contract Methods: ${parsedContractMethodsResult.error}`,
            },
          ],
        };
      }
      const parsedContractMethods = parsedContractMethodsResult.value;
    
      return {
        content: [
          {
            type: 'text',
            text: stringify_bigint(parsedContractMethods),
          },
        ],
      };
    },
  • Zod input schema defining parameters: contractId (string), methodName (string), networkId (testnet/mainnet, default mainnet).
      contractId: z.string(),
      methodName: z.string(),
      networkId: z.enum(['testnet', 'mainnet']).default('mainnet'),
    },
  • Helper function to retrieve and parse the contract's ABI from the __contract_abi view method, used as primary source for function arguments.
    const getContractABI = async (
      account: Account,
      contractAccountId: string,
    ): Promise<Result<AbiRoot, Error>> => {
      try {
        const contractABICompressed: unknown = await account.viewFunction({
          contractId: contractAccountId,
          methodName: '__contract_abi',
          args: {},
          parse: (value) => value,
        });
    
        const decoder = new ZSTDDecoder();
        await decoder.init();
        const contractABI = new TextDecoder().decode(
          decoder.decode(contractABICompressed as Buffer),
        );
        return {
          ok: true,
          value: JSON.parse(contractABI) as AbiRoot,
        };
      } catch (e) {
        return { ok: false, error: new Error(e as string) };
      }
    };
  • Fallback helper: Queries nearblocks.io API for recent executions of the method to infer argument structure from args_json.
    export const getParsedContractMethod = async (
      contractId: string,
      methodName: string,
    ): Promise<Result<ParsedMethod, Error>> => {
      try {
        const url = `https://api.nearblocks.io/v1/account/${contractId}/contract/${methodName}`;
        const response = await fetch(url);
        const responseJson = (await response.json()) as unknown;
        const parsedMethod = ParsedMethodSchema.safeParse(responseJson);
        if (!parsedMethod.success) {
          return {
            ok: false,
            error: new Error(
              `Error parsing args for contract ${contractId}, method ${methodName}. Got: ${JSON.stringify(
                responseJson,
                null,
                2,
              )}`,
            ),
          };
        }
        return {
          ok: true,
          value: parsedMethod.data,
        };
      } catch (error) {
        return {
          ok: false,
          error: new Error(
            `Error parsing contract method ${methodName} for contract ${contractId}: ${String(error)}`,
          ),
        };
      }
Behavior3/5

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

With no annotations provided, the description carries full burden. It discloses the experimental nature and lack of guarantee, which is valuable behavioral context. However, it doesn't mention rate limits, authentication needs, whether it performs network calls, or what happens on failure. The warning adds some transparency but leaves key operational aspects unspecified.

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

Conciseness4/5

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

The description is appropriately concise with three sentences that each add value: the core purpose, implementation details, and warning. It's front-loaded with the main function and avoids unnecessary elaboration. However, the misspelling 'garunteed' slightly detracts from professionalism.

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

Completeness2/5

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

For a tool with 3 parameters (0% schema coverage), no annotations, and no output schema, the description is insufficient. It doesn't explain parameter meanings, expected return values, error conditions, or how the ABI parsing versus API fallback works. The experimental warning is helpful but doesn't compensate for missing operational context.

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

Parameters2/5

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

Schema description coverage is 0%, so the description must compensate for undocumented parameters. It mentions parsing ABI or using nearblocks.io API, which hints at contractId and methodName usage, but doesn't explain what these parameters mean, their formats, or the networkId parameter's role. The description adds minimal semantic value beyond the bare schema.

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 clearly states the tool's purpose: 'Get the arguments of a function call' by parsing ABI or using an API fallback. It specifies the resource (contract function) and method (parsing/API checking), but doesn't explicitly differentiate from sibling tools like contract_call_raw_function or contract_view_functions beyond mentioning its experimental nature.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives like contract_call_raw_function or contract_view_functions. It mentions it's experimental and not guaranteed to be correct, but doesn't specify use cases, prerequisites, or exclusions relative to sibling tools.

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

Related 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/nearai/near-mcp'

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