Skip to main content
Glama
sammcj

Bybit MCP Server

by sammcj

get_positions

Retrieve real-time position details for authenticated users on Bybit, filtering by category, symbol, base coin, or settle coin. Simplify trading analysis with structured data output.

Instructions

Get positions information for the authenticated user

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
baseCoinNoBase coin. Used to get all symbols with this base coin
categoryYesProduct type
limitNoMaximum number of results (default: 200)
settleCoinNoSettle coin. Used to get all symbols with this settle coin
symbolNoTrading symbol, e.g., BTCUSDT

Implementation Reference

  • The `toolCall` method provides the execution logic for the 'get_positions' tool: validates input using Zod schema, prepares parameters, fetches position data from Bybit API, formats the response, and handles errors.
    async toolCall(request: z.infer<typeof CallToolRequestSchema>) {
      try {
        this.logInfo("Starting get_positions tool call")
    
        // Parse and validate input
        const validationResult = inputSchema.safeParse(request.params.arguments)
        if (!validationResult.success) {
          throw new Error(`Invalid input: ${validationResult.error.message}`)
        }
    
        const {
          category,
          symbol,
          baseCoin,
          settleCoin,
          limit = "200"
        } = validationResult.data
    
        this.logInfo(`Validated arguments - category: ${category}, symbol: ${symbol}, limit: ${limit}`)
    
        // Prepare request parameters
        const params: PositionInfoParamsV5 = {
          category,
          symbol,
          baseCoin,
          settleCoin,
          limit: parseInt(limit, 10)
        }
    
        // Execute API request with rate limiting and retry logic
        const response = await this.executeRequest(async () => {
          return await this.getPositionsData(params)
        })
    
        // Format response
        const result: FormattedPositionsResponse = {
          category,
          symbol,
          baseCoin,
          settleCoin,
          limit: parseInt(limit, 10),
          data: response.list,
          timestamp: new Date().toISOString(),
          meta: {
            requestId: crypto.randomUUID()
          }
        }
    
        this.logInfo(`Successfully retrieved positions data${symbol ? ` for ${symbol}` : ''}`)
        return this.formatResponse(result)
      } catch (error) {
        this.logInfo(`Error in get_positions: ${error instanceof Error ? error.message : String(error)}`)
        return this.handleError(error)
      }
    }
  • The `toolDefinition` property defines the input schema, description, and metadata for the 'get_positions' tool, used for MCP tool listing and validation.
    toolDefinition: Tool = {
      name: this.name,
      description: "Get positions information for the authenticated user",
      inputSchema: {
        type: "object",
        properties: {
          category: {
            type: "string",
            description: "Product type",
            enum: ["linear", "inverse"],
          },
          symbol: {
            type: "string",
            description: "Trading symbol, e.g., BTCUSDT",
          },
          baseCoin: {
            type: "string",
            description: "Base coin. Used to get all symbols with this base coin",
          },
          settleCoin: {
            type: "string",
            description: "Settle coin. Used to get all symbols with this settle coin",
          },
          limit: {
            type: "string",
            description: "Maximum number of results (default: 200)",
            enum: ["1", "10", "50", "100", "200"],
          },
        },
        required: ["category"],
      },
    }
  • The `loadTools` function dynamically scans the src/tools directory, imports and instantiates tool classes like GetPositions, validating they extend BaseToolImplementation, and returns the list of loaded tools for registration.
    export async function loadTools(): Promise<BaseToolImplementation[]> {
      try {
        const toolsPath = await findToolsPath()
        const files = await fs.readdir(toolsPath)
        const tools: BaseToolImplementation[] = []
    
        for (const file of files) {
          if (!isToolFile(file)) {
            continue
          }
    
          try {
            const modulePath = `file://${join(toolsPath, file)}`
            const { default: ToolClass } = await import(modulePath)
    
            if (!ToolClass || typeof ToolClass !== 'function') {
              console.warn(JSON.stringify({
                type: "warning",
                message: `Invalid tool class in ${file}`
              }))
              continue
            }
    
            const tool = new ToolClass()
    
            if (
              tool instanceof BaseToolImplementation &&
              tool.name &&
              tool.toolDefinition &&
              typeof tool.toolCall === "function"
            ) {
              tools.push(tool)
              console.info(JSON.stringify({
                type: "info",
                message: `Loaded tool: ${tool.name}`
              }))
            } else {
              console.warn(JSON.stringify({
                type: "warning",
                message: `Invalid tool implementation in ${file}`
              }))
            }
          } catch (error) {
            console.error(JSON.stringify({
              type: "error",
              message: `Error loading tool from ${file}: ${error instanceof Error ? error.message : String(error)}`
            }))
          }
        }
    
        return tools
      } catch (error) {
        console.error(JSON.stringify({
          type: "error",
          message: `Failed to load tools: ${error instanceof Error ? error.message : String(error)}`
        }))
        return []
      }
    }
  • Private helper method `getPositionsData` that calls the Bybit API's `getPositionInfo` endpoint to retrieve raw position data.
    private async getPositionsData(
      params: PositionInfoParamsV5
    ): Promise<APIResponseV3WithTime<{ list: PositionV5[] }>> {
      this.logInfo(`Fetching positions with params: ${JSON.stringify(params)}`)
      return await this.client.getPositionInfo(params)
    }
  • src/index.ts:134-135 (registration)
    In the main function, `loadTools()` is called to load tools including 'get_positions', and `createToolsMap` populates the toolsMap used by MCP request handlers for tool listing and execution.
    const tools = await loadTools()
    toolsMap = createToolsMap(tools)
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states it retrieves information (implying read-only), but doesn't cover aspects like authentication requirements, rate limits, response format, or potential side effects, which are critical for a financial tool.

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?

The description is a single, efficient sentence that directly states the tool's purpose without unnecessary words. It's appropriately sized and front-loaded, making it easy to parse quickly.

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?

Given the complexity of a financial positions tool with 5 parameters and no output schema, the description is insufficient. It lacks details on return values, error handling, or behavioral context, leaving significant gaps for the agent to operate effectively.

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?

The schema description coverage is 100%, so the schema already documents all parameters thoroughly. The description adds no additional parameter information beyond what's in the schema, meeting the baseline for high coverage but not enhancing understanding.

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 action ('Get') and resource ('positions information'), specifying it's for the authenticated user. However, it doesn't differentiate from sibling tools like 'get_wallet_balance' or 'get_order_history' that might also retrieve user-specific financial data, so it lacks sibling distinction.

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. It doesn't mention use cases, prerequisites, or exclusions, leaving the agent to infer usage from the tool name and parameters alone.

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/sammcj/bybit-mcp'

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