Agentic tradingMCPDevelopersStocks

How to build a stock trading agent with MCP

A developer guide to connecting AI agents to stock markets through MCP, with safety controls, dollar sizing, and non-custodial keys.

By the Felix team10 min read
Key takeaways
  • 01MCP lets an AI agent call trading tools as standard functions, but the developer must still constrain the tool set and system prompt.
  • 02Scoped keys let the agent trade without taking custody, and withdrawal permissions remain exclusive to the owner.
  • 03Orders sized in plain US dollars remove the need for the agent to calculate share counts or venue-specific lot rules.
  • 04Hard limits such as budget caps and position limits are enforced by the infrastructure, not by the model's compliance.
  • 05Paper trading and explicit live authorization let developers test behavior before real money is at risk.

A developer can connect an AI agent to stock markets through the Model Context Protocol by treating trading tools as standard functions the model can call. The agent reads market data, decides whether to trade, and sends orders through a single API that normalizes venue-specific logic. Because the setup is non-custodial, the owner keeps control of the funds and approves both the scoped key and any withdrawal addresses. The agent can only spend within predefined limits, and a panic switch can revoke access instantly.

What does MCP add to a stock trading agent?

MCP turns a trading API into a set of discoverable tools that an LLM can invoke. Instead of writing custom glue code between a broker's API and your model, you expose functions like get_quote, view_portfolio, and place_order through an MCP server. The model, running in Claude, Cursor, or another MCP client, sees these as typed functions with descriptions. When the agent decides it wants to buy a stock, it emits a tool call. The MCP layer routes that call to the trading infrastructure, which validates it against safety controls before it reaches the market.

This architecture changes who writes the integration logic. The developer does not need to parse the agent's natural language output into API requests manually. The model outputs structured JSON arguments that match the tool schema. However, this convenience introduces a new class of risks. An LLM can hallucinate tickers, misinterpret its own portfolio state, or loop on a losing strategy because it treats trading as a text puzzle rather than a financial operation. MCP makes the plumbing easy, but the developer is still responsible for defining the system prompt, constraining the tool set, and setting hard limits that the infrastructure enforces regardless of what the model thinks.

For stock trading specifically, the agent does not need to understand lot sizes, exchange hours, or order types beyond what the tool descriptions explain. The developer can keep the tool surface narrow. For example, the agent might only be allowed to place day orders denominated in dollars, not after-hours limit orders sized in shares. This restriction happens at the infrastructure level, not by asking the model nicely. The result is that the agent can focus on strategy while the platform handles execution mechanics.

How do scoped keys work without custody?

The first step in building a stock trading agent is creating a key that lets the agent trade but never lets it take custody of the funds. Felix uses scoped API keys that bind to a specific wallet or brokerage account that the owner controls. The agent can spend within the budget, but it cannot withdraw funds to an external address, change withdrawal settings, or revoke the owner's own access. This is non-custodial by construction, not by policy promise.

When a developer creates a scoped key, they define the exact permissions it carries. A stock trading key might allow placing and canceling orders, reading balances, and viewing positions. It cannot request account withdrawals or update bank details. The owner maintains the master credentials and can rotate or revoke the agent's key at any time without waiting for the agent to cooperate. This means a compromise of the agent host does not automatically mean a compromise of the account.

This matters because an AI agent is a software process that may run autonomously for hours or days. If the host machine is infected, or if the model is tricked into emitting a malicious tool call, the attacker is trapped inside the permission scope of that key. They cannot drain the account. They can only trade within the caps the owner set. You can read more about this design in How scoped API keys let an agent trade without taking custody of your funds.

Developers should treat the scoped key as a blast radius limiter. Even if your agent logic is perfect, the machine it runs on could be breached, or the MCP client could have a vulnerability. A scoped key ensures that the worst-case scenario is a controlled loss, not a total account wipe. The key is a structural safety feature, not a convenience layer.

How does dollar sizing simplify stock orders?

One of the most error-prone parts of algorithmic trading is order sizing. An agent that calculates share counts manually can easily slip a decimal point, confuse notional value with quantity, or ignore minimum order sizes. Felix abstracts this by accepting orders denominated in plain US dollars. The developer tells the agent to buy or sell a dollar amount, and the infrastructure translates that into the correct number of shares, fractional if needed, at the current market price.

This normalization is especially useful for stock trading because different brokers handle fractional shares, odd lots, and commissions differently. The agent does not need to know these rules. It reasons in dollars, which aligns with how most people think about portfolio allocation. If the agent decides to allocate five percent of a ten thousand dollar portfolio to a single stock, it can simply request a five hundred dollar buy. The API handles the share math and any rounding.

Dollar sizing also makes risk controls easier to reason about. A developer can set a per-order cap of one thousand dollars and a daily budget cap of five thousand dollars. The agent understands these numbers naturally because they match the units it uses for portfolio value. There is no translation layer where the agent must convert a dollar risk limit into a share count using a live price. The infrastructure enforces the dollar limit directly. For more on placing trades across market types, see How to place your first automated trade in any market with one API.

The trade-off is that the agent has less control over exact share quantities. For most discretionary stock strategies, this is an advantage. It prevents the model from over-optimizing on odd lot sizing or trying to game commission structures it does not fully understand. The developer gets consistency, and the agent gets a simpler action space.

Where do safety controls fit in the execution loop?

Safety controls are not an afterthought. They are the primary interface between the agent's intent and the market. Before the agent ever sees a quote, the developer configures budget caps, position limits, approved tickers, and a kill switch. These limits live in the infrastructure, not in the agent's prompt. The agent cannot negotiate them away, prompt-inject around them, or accidentally override them with a malformed tool call.

When the agent emits a buy order, the request passes through a validation layer. Is the ticker on the approved list? Does the order notional exceed the per-trade cap? Will this trade push the total position beyond the maximum allowed? Is the daily spend budget already exhausted? If any check fails, the infrastructure rejects the order and returns an error to the agent. The agent can then decide what to do next, but it cannot force the trade through.

A kill switch or panic button serves as an emergency brake. If the market moves violently, or if the agent begins behaving erratically, the owner can hit the switch. This flattens open positions where possible and revokes the agent's key immediately. The agent does not get a veto. The owner remains in control because the funds and the master keys are theirs.

Hard limits also prevent the model from drifting. An LLM agent running over a long session might develop a flawed theory about market patterns and start doubling down. A daily loss cap or maximum position size stops this drift mechanically. The model is free to reason, but it is not free to spend without bounds. This is described in How autonomous trading systems enforce hard limits the agent cannot cross.

Developers should configure these limits before writing the agent's personality. It is tempting to start with an open prompt and add constraints later. That approach is dangerous. Set the guardrails first, then give the agent a narrow tool set, and only then let it reason about strategy. The infrastructure must be the final authority, not the model.

What does a trade request look like in practice?

When an agent decides to trade, the MCP client sends a tool call to the Felix server. The developer does not need to write raw HTTP requests because the MCP layer handles transport, but understanding the payload shape helps with debugging and testing. The exact request schema is in the docs; the shape looks like this.

{
  "name": "place_order",
  "arguments": {
    "market_type": "stock",
    "ticker": "AAPL",
    "side": "buy",
    "notional_usd": 500,
    "time_in_force": "day"
  }
}

The response includes an order identifier, a status, and the filled notional amount. The agent can then call a portfolio tool to confirm the new position. Because the infrastructure validates the order against the scoped key and the safety limits, a malformed or oversized request returns an error before it reaches the market. The agent sees that error and can incorporate it into its reasoning, but it cannot bypass the check.

What should you verify before authorizing live trading?

Before the agent touches real money, run it in paper trading mode. Paper trading uses live market data but simulates execution, so the agent can demonstrate its decision loop without risk. Watch for repetitive patterns, hallucinated tickers, and failure to handle rejection errors. If the agent loops on a failed order or invents symbols that do not exist, fix the prompt or tighten the tool descriptions before going live.

Live trading requires an explicit owner authorization step. The scoped key must be upgraded from paper to live, and the owner must confirm this action. The developer cannot accidentally flip a boolean and start trading real money. This deliberate friction protects against configuration mistakes.

Verify the kill switch. Place a small paper trade, then trigger the panic button. Confirm that the key is revoked and that positions are flattened according to your exit plan. Test the daily budget cap by attempting to exceed it in paper mode. Confirm that the position limit blocks an order that would put you over the maximum. These tests are not optional. An untested safety control is a fiction.

Finally, review the agent's reasoning traces. MCP clients often show the model's chain of thought alongside tool calls. Check whether the agent is trading on fabricated news, misreading its own holdings, or ignoring risk instructions in the system prompt. The model is probabilistic, and trading can lose money, including everything. No safety control can make a bad strategy profitable. It can only make the losses bounded and the owner sovereign. For a broader checklist on taking an agent live, see How to build a trading agent that handles real money safely.

Frequently asked questions

Does the agent need to know my broker's API?

No. The Felix API abstracts the underlying venue. The agent calls Felix tools such as place_order or get_quote, and the infrastructure translates those into the correct venue-specific requests. The developer does not need to write custom integration code for each broker, and the agent does not need to understand venue-specific order types or session rules.

Can the agent withdraw funds to its own wallet?

No. Scoped keys are created without withdrawal permissions. The agent can place and cancel trades within its budget, but it can never move funds out of the account or add new withdrawal addresses. Only the owner, using the master credentials, can initiate a withdrawal.

What happens if the agent tries to exceed its budget cap?

The infrastructure rejects the order before it reaches the market. The agent receives an error response and can reason about how to adjust its strategy, but it has no mechanism to override the limit. These hard limits are enforced by the trading infrastructure, not by the model's willingness to comply.

Is paper trading available for stock strategies?

Yes. Paper trading lets the agent run against live market data with simulated execution. It is the recommended starting point for any new strategy. Moving to live trading requires an explicit owner authorization step that upgrades the scoped key.

Can I use this with Claude, Cursor, or other MCP clients?

Yes. Felix exposes trading tools through the Model Context Protocol. Any MCP client, including Claude, Cursor, and other compatible agents, can discover these tools and invoke them. The developer configures which tools are available and what the system prompt says about risk.

What if the model hallucinates a ticker symbol?

The infrastructure will reject an order for an unrecognized or disallowed ticker. However, developers should still review the agent's reasoning traces regularly to catch hallucinations, logic loops, or misinterpretations of portfolio state. A narrow approved-ticker list and strict tool descriptions reduce the frequency of these errors.

Give your agent a key.

One key to trade stocks, crypto, perps, options, and prediction markets. Live after owner authorization.

Keep reading

Not a brokerage, exchange, or investment adviser. Not investment advice. Trading involves risk, including total loss.