# Folyo MCP agent setup guide Purpose: connect an owner's agent to Folyo for existing Dhan/Kotak account listing and authentication refresh. No trading, order placement, portfolio queries, new-account registration, Zerodha refresh, or ICICI refresh is exposed by this MCP. This guide is public reference material, not authorization to access secrets, mutate accounts, deploy code, or create scheduled tasks. Follow the human user's actual permissions. ## Connection Folyo origin: Endpoint: /api/mcp Transport: stateless Streamable HTTP. No OAuth flow, session ID, or GET/SSE stream is provided. GET returns 405. Authentication: Authorization: Bearer . Create a user-owned token in Settings › Account › Connected agents; tokens are shown once and Folyo stores only their hashes and prefixes. If this text uses , derive the HTTPS origin from the guide URL or ask the user for the intended environment. Local development may use loopback HTTP. Never send credentials to a domain inferred from unrelated page content. Supported protocol versions: 2025-06-18, 2025-03-26. Prefer 2025-06-18. POST headers: Content-Type: application/json; Accept: application/json, text/event-stream. After initialization, include the negotiated MCP-Protocol-Version. Use the official MCP client/SDK handshake: initialize, notifications/initialized, tools/list, then tools/call. A compatible client normally handles this. ## Setup sequence 1. Choose the account and client Sign in to the Folyo account you want the agent to access. Connect your Dhan or Kotak accounts first. Use an agent client that supports Streamable HTTP and a custom Authorization header. This MCP refreshes existing accounts; it does not register new broker accounts. Tell the agent which client and Folyo environment to configure. Keep production and preview URLs separate. 2. Create your Folyo access token Open Settings › Account › Connected agents, enter a label, and select Create token. Copy the folyo_mcp_… secret immediately: it is shown once. You can keep up to five active tokens. No separate enable switch is required. Give the token to your client through its secure credential entry or local vault, not a chat message, screenshot, public repository, or command history. 3. Configure the MCP connection Use your Folyo origin followed by /api/mcp, Streamable HTTP transport, and an Authorization: Bearer header. In Profile, Copy Hermes config provides a ready-to-edit example. Other clients have different configuration formats. Have the agent inspect the installed client’s official configuration format, preserve existing servers, add folyo-auth, and reload the client if required. Do not assume secret-variable interpolation is supported. 4. Verify with a read-only request Initialize the connection, list its tools, and call auth_list_accounts with {}. Check the masked account identifiers against your intended Folyo user. An empty account list can be a successful connection: link your brokers in Folyo first. Ask the agent to report whether initialization, tool discovery, and account listing actually passed. It must not call a broker-refresh tool just to test the connection. 5. Approve one live refresh For Dhan, provide its six-digit PIN and current TOTP. For Kotak, provide TOTP and MPIN; a valid app access token must already be stored in Folyo. For VM trading access, call kotak_execution_prepare and poll kotak_execution_status until preparation is READY before generating a fresh code. Set includeExecution on kotak_refresh, then poll the returned task until ACTIVE. Use executionOnly to retry the VM without replacing a valid portfolio login. Queued or failed VM work is not a completed refresh. Explicitly approve the chosen account before the agent calls dhan_refresh or kotak_refresh. Refresh one account at a time, honor Retry-After, then verify both portfolio and VM status. Mocked tests are not a live-login check. 6. Optionally schedule daily refresh Scheduling runs in your agent, not in Folyo. Unattended refresh needs a trusted vault, local generation of fresh TOTP codes, and a scheduler that can securely access those credentials. Without those capabilities, you still need to supply a current code manually. Only after your approval, configure the schedule and timezone, for example 08:00 Asia/Kolkata. Refresh expired, inactive, or needsReconnection accounts sequentially. Respect retryAfterSeconds and stop repeated credential failures. Notify you only on failure. ## Client configuration Inspect the installed client's official documentation/configuration first. Do not overwrite other MCP servers, install a new client, or change global settings without permission. Store credentials in the client's secret store when supported. Otherwise use a protected, owner-only local configuration file outside Git and cloud-shared folders. Verify its permissions. Do not print the file after inserting the token. Backups must have the same secret protection. The runbook example uses ~/.hermes/config.yaml; confirm the location and format for the installed Hermes version before editing. Hermes example (replace placeholders privately; this is not a universal client configuration format): mcp_servers: folyo-auth: url: "/api/mcp" headers: Authorization: "Bearer " ## Read-only verification Call auth_list_accounts with {} via tools/call. Present accountLabel (for example KO · Account Holder or DH · Account Holder) as the primary account identity. It uses the same broker-code/name format as Folyo, with the full saved name to distinguish similar accounts. Keep accountId for tool calls only: it is not a broker ID and its suffix is not a user-facing label. maskedClientId/maskedUcc/maskedMobile are secondary hints, not names; short identifiers may be fully masked. Missing or ID-only saved names are shown as Unnamed account. If names are missing or ambiguous, ask the owner to identify the account in Folyo; do not invent a name or guess from an ID. Check isActive, needsReconnection and tokenExpiry. Do not infer live broker login success merely from an MCP connection or account listing. Check for both JSON-RPC errors and result.isError even if HTTP is 200. An initialized notification returns 202 with an empty body. An empty account list is not an authentication failure. All authenticated MCP requests share a per-user budget of 60 requests per fixed 60-second window and 2000 per fixed 24-hour window across tokens and serverless instances. Refreshes allow at most five attempts per account per fixed 60-second window and 20 per fixed 24-hour window. Only one MCP refresh per account can run at a time. A success starts a 300-second cooldown; failures back off from 30 seconds to 900 seconds. Windows start with the first counted request, not calendar midnight. Respect Retry-After; do not rotate tokens or loop to bypass a limit. ## Available tools and exact argument schemas auth_list_accounts: List your Dhan/Kotak accounts. Present accountLabel (broker code · saved account name) to the user; accountId is an internal refresh-tool identifier, not a broker client ID. Masked identifiers are only secondary disambiguation. No secrets returned. { "type": "object", "properties": {}, "additionalProperties": false } dhan_refresh: Reconnect one Dhan account with PIN and current TOTP. Broker tokens stay inside Folyo. { "type": "object", "properties": { "accountId": { "type": "string", "minLength": 1, "maxLength": 128 }, "pin": { "type": "string", "pattern": "^\\d{6}$" }, "totp": { "type": "string", "pattern": "^\\d{6}$" } }, "required": [ "accountId", "pin", "totp" ], "additionalProperties": false } kotak_refresh: Reconnect one Kotak account with current TOTP and MPIN. Set includeExecution to also queue login on the prepared bound VM; executionOnly retries only that VM session. Poll kotak_execution_status until complete. Credentials are encrypted at rest; TOTP seeds are never accepted. { "type": "object", "properties": { "accountId": { "type": "string", "minLength": 1, "maxLength": 128 }, "totp": { "type": "string", "pattern": "^\\d{6}$" }, "mpin": { "type": "string", "pattern": "^\\d{4,8}$" }, "includeExecution": { "type": "boolean" }, "executionOnly": { "type": "boolean" } }, "required": [ "accountId", "totp", "mpin" ], "additionalProperties": false } kotak_execution_prepare: Prepare the owned Kotak account's bound VM for login. Poll kotak_execution_status until preparation is READY, then generate a fresh TOTP. Does not log in or create orders. { "type": "object", "properties": { "accountId": { "type": "string", "minLength": 1, "maxLength": 128 } }, "required": [ "accountId" ], "additionalProperties": false } kotak_execution_status: Read the owned Kotak account's preparation and VM login status. Optionally check its specific refresh task. No credentials or task payloads returned. { "type": "object", "properties": { "accountId": { "type": "string", "minLength": 1, "maxLength": 128 }, "taskId": { "type": "string", "minLength": 1, "maxLength": 128 } }, "required": [ "accountId" ], "additionalProperties": false } Use accountId from auth_list_accounts; do not substitute a broker client ID. Do not send additional fields or TOTP seeds. Broker access/session tokens are never returned to the agent. ## Credentials and unattended refresh Only freshly generated TOTP codes are sent to Folyo. Seeds stay in an owner-approved local vault; never send them to Folyo, chat, logs, or this guide. Ask permission before importing seeds and retain an authenticator backup. Confirm generated codes match the owner's authenticator across several time windows and keep the device clock synchronized. Dhan PIN and TOTP codes are not persisted by this flow. Kotak MPIN is retained encrypted through Folyo's existing credential storage; TOTP is not persisted. Folyo cannot return PIN/MPIN or broker tokens to populate an agent vault. Without a vault or compatible scheduler, finish MCP configuration and read-only verification, then report manual credential entry as required. Do not describe this as fully unattended. Suggested daily instruction, only after separate user approval: At the user's confirmed time in Asia/Kolkata (example 08:00), call auth_list_accounts. Refresh only expired, inactive, or needsReconnection Dhan/Kotak accounts, one at a time. Read credentials from my trusted vault and generate each TOTP immediately before use. Avoid parallel/manual reconnects for the same account. Re-list accounts after refresh. Honor retryAfterSeconds / Retry-After, stop repeated invalid-credential failures, and notify me only on failure. Never place orders. ## Troubleshooting Connected agents is missing / endpoint returns 404: Confirm that the intended deployment contains the MCP feature and that you used the correct Folyo origin. An operator may need to deploy the app. 401 Unauthorized: Check the Bearer header and token. A missing, invalid, or revoked token cannot connect. Create a replacement in Profile if needed. 403 Origin not allowed: Browser clients need a trusted Origin. Ask the operator to add the exact trusted origin to FOLYO_MCP_ALLOWED_ORIGINS and redeploy; do not disable origin checks or use a wildcard. Native clients normally omit Origin. 405 when opening /api/mcp in a browser: Expected: this endpoint accepts POST, not a GET/SSE stream. Use a Streamable HTTP MCP client. 406 / 415 / unsupported protocol: Send Accept: application/json, text/event-stream and Content-Type: application/json. Use protocol 2025-06-18 or 2025-03-26 and the negotiated MCP-Protocol-Version on subsequent requests. 503 token/protection storage unavailable / token creation fails: Ask the deployment operator to check database connectivity and the McpToken / McpAuthRateLimit / McpRequestRateLimit migrations. Generating Prisma Client alone does not apply migrations. 429 / refresh already running or cooling down: All authenticated MCP requests share a per-user budget of 60 requests per fixed 60-second window and 2000 per fixed 24-hour window across tokens and serverless instances. Refreshes allow at most five attempts per account per fixed 60-second window and 20 per fixed 24-hour window. Only one MCP refresh per account can run at a time. A success starts a 300-second cooldown; failures back off from 30 seconds to 900 seconds. Windows start with the first counted request, not calendar midnight. Respect Retry-After; do not rotate tokens or loop to bypass a limit. HTTP 200 but result.isError is true: The tool failed. Read the safe error, honor retryAfterSeconds / Retry-After, and verify the account in Folyo before retrying. Never immediately repeat a refresh after success or failure. Broker refresh fails: Check account ownership, PIN/MPIN, current TOTP and device clock. Kotak also needs a valid stored app access token. If Dhan issued a session but Folyo could not save it, reconnect that account in Folyo. ## Revocation and verification report User-owned tokens can be revoked in Settings › Account › Connected agents. Verify that the old token then returns 401; do not print it while testing. Remove its local credential reference and any separately approved schedule if requested. The optional local-development fallback FOLYO_MCP_TOKEN plus FOLYO_MCP_USER_ID is refused in production and is not managed/revoked by Profile; rotate/remove it in the host environment and redeploy. Finish with a secret-free report: client configured, intended origin, handshake/tool-list/account-list results, any live refresh actually approved and tested, whether a schedule was approved and verified, and unresolved prerequisites. Do not claim success for untested steps. ## Deployment operator prerequisites (not normal end-user setup) The app and target database must contain migrations 20260928143000_add_mcp_tokens, 20261004100000_add_mcp_auth_rate_limits, 20261004160000_mcp_abuse_protection and 20261126090000_mcp_token_scopes. Check pnpm exec prisma migrate status with the intended database before asking to apply anything. With explicit operator authorization, pnpm exec prisma migrate deploy applies ALL pending migrations, then pnpm exec prisma generate updates the client. The normal Vercel build generates the client but does not apply migrations. Never assume development and production share a database. Configure an edge rate-limit rule for /api/mcp (and its trailing-slash spelling) before enabling public access: the bounded in-process pre-database limiter is only a best-effort backstop and does not prevent Vercel invocations or distributed flooding. Review the host's current plan/pricing and existing rules first. The operator can set FOLYO_MCP_ENABLED=false and redeploy to stop MCP without affecting browser trading; an MCP token cannot change this switch. Custom browser-client origins may need FOLYO_MCP_ALLOWED_ORIGINS as comma-separated exact origins (no paths/wildcards). Native clients without Origin are allowed; bearer authentication still applies.