foxmayn_frappe_cli
CLAUDE.md16 starsChanged 37 days agoMITView on GitHub
ffc (Foxmayn Frappe CLI) — A Go CLI for interacting with Frappe ERP sites via the REST API. make build | test | lint | vet | fmt | vuln (see the Makefile). Version info is injected through ldflags. make lint runs staticcheck from tools/lint/go.mod, its own module. Tag vX.Y.Z and push it: GoReleaser + GitHub Actions (.github/workflows/release.yml) build, sign and publish the archives, the .mcpb bundle, the signed checksums.txt and the MCP Registry entry. Details, signing keys and rotation:…
- Reads credentials
In this repository13 other files it gives its agents.
- desktop/CLAUDE.mdCLAUDE.md
- ffc-bulk-lifecycleSkill
- ffc-coreSkill
- ffc-dev-clientSkill
- ffc-dev-commandSkill
- ffc-dev-desktopSkill
- ffc-dev-mcp-toolSkill
- ffc-devSkill
- ffc-dev-testingSkill
- ffc-files-collabSkill
- ffc-mcpSkill
- ffc-reports-apiSkill
- ffc-setupSkill
The file
We split this CLAUDE.md into the rules it gives an agent
3 rules. About 0 are common, 1 is distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 49
Every new command or tool ships with tests against the fake.
- Very specific: line 65
Default config path: ~/.config/ffc/config.yaml (dir 0700, file 0600, lock file config.yaml.lock).
- Very specific: line 84
Retries: only GET, on 429/502/503/504 and on transport errors, never after a timeout or cancel, a refused redirect or a TLS/certificate …
≈ “Common” is an estimate: at least 1 in 5 of the 27,641 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
CLAUDE.md — Project Context for AI Agents
Project
ffc (Foxmayn Frappe CLI) — A Go CLI for interacting with Frappe ERP sites via the REST API.
Build & Run
make build | test | lint | vet | fmt | vuln (see the Makefile). Version info is injected through ldflags. make lint runs staticcheck from tools/lint/go.mod, its own module.
Release
Tag vX.Y.Z and push it: GoReleaser + GitHub Actions (.github/workflows/release.yml) build, sign and publish the archives, the .mcpb bundle, the signed checksums.txt and the MCP Registry entry. Details, signing keys and rotation: docs/development/internals/release.md. Never commit a private key. Desktop releases use desktop-vX.Y.Z tags and never become GitHub's "latest": see desktop/CLAUDE.md.
Architecture
Entry point cmd/ffc/main.go → internal/cmd (cobra). Find the rest with ls internal/* and grep; these are the rules the layout does not show:
internal/cmd/site_client.go:loadSite(=loadSiteConfig, no network, +refreshSite, OAuth refresh under the config lock) andnewClientare the ONLY way a command or MCP tool gets a site client.internal/cmd/helpers.go:callSite[T](client + spinner),runSpinner,confirm,readInput("-" = stdin),parseObject,splitCSV,filterKeys/selectKeys,listLimit,docName,validateFiltersJSON.internal/cmd/render.gois the output layer (render,machineOutput/printResult,listDocs).internal/sitesetup/never prompts or exits and has no huh/cobra;internal/cmdimports it, never the reverse.internal/loopback,internal/sitecache,internal/release,internal/desktopinstallandinternal/mcpinstallare prompt- and cobra-free too (the desktop imports them).internal/clientmay still warn on stderr (plain-HTTP warning,--debugtrace).internal/client: onedo()request path (client.go), transport inhttp.go,raw.go(SitePath,CheckHeaders) is the credential boundary,debug.goholds the redaction helpers.internal/config/file.go: every config write goes throughEdit/Overwrite(see Common Pitfalls).internal/output+internal/text: every server value passes throughtext.Sanitize.internal/cmd/update_check.goownsrootCmd.PersistentPreRunE.internal/cmd/desktop.go:ffc desktop status|install, a non-site command overinternal/desktopinstall(the desktop app shares it).desktopErrormaps its errors to exit codes; tests swapdesktopGOOS,newDesktopInstaller,desktopLocate.- MCP:
mcp_args.gotoolHandlerruns parse → scope → policy → confirm → client → call → audit line; tools are registered inmcp_tools.go(and its siblings), their policy tablestoolActions/toolSurfacelive inmcp_policy.go. desktop/is a nested Go module;tools/(relsign, gendocs, mcpb, lint) is build tooling and is not shipped.
Subsystem notes
Detail moved out of this file. Read the file before changing that area; the headline rule is repeated here.
docs/development/internals/mcp.md: MCP policy, confirmation, multi-site, restore_doc, embedding,ffc mcp install, tool surface, jq, limits. Config may loosen the site policy but theffc mcpflags only narrow it;applyEnvOverridesandFile.PutSitemust keep themcpblock (dropping it widens access).scopeOfrefusesignore_permissions/ignore_user_permissionsin call_method args, with no config switch.docs/development/internals/oauth.md: refresh, dynamic registration, revocation. OAuth refresh lives inloadSiteand the client'stokenRefresher, never inPersistentPreRunE.docs/development/internals/erp.md:ffc erpand the MCP erp tools. Never sendignore_permissionsto an ERPNext mapper (MapDocsends onlysource_name).docs/development/internals/import-export.md: export, import-template, import (client side and--server). Import checks everything before any write; Password fields are a usage error and their values are never printed.docs/development/internals/customize-admin.md:customize pull/push,health/jobs/errors/scheduler. A Password field sent empty deletes the stored secret, so push never sends one; push never deletes.docs/development/internals/data-commands.md: identity and permissions, server version cache, doctor, lifecycle, bulk-create--atomic, local cache and completion, get-doc--fields, optimistic concurrency, search, aggregates, prepared reports, doc-info, collaboration, files and PDF. The doctor check ids are a JSON contract: never rename them. A tool that needspolicyFromfails without one, never falls back to the zero policy.docs/development/internals/release.md: release flow, signing, key rotation, MCP Registry.desktop/CLAUDE.mdloads by itself underdesktop/(Assistant rules, safety rules, i18n, bindings).
Testing
- Fake Frappe (
internal/frappetest). An in-memory site for unit tests:/api/resourceCRUD with filters, fields, paging and ordering, the/api/methodendpoints ffc calls, files (upload_file, attach_file, /files and /private/files, download_pdf, get_html_and_style; files.go), API-key/Bearer/session auth, login and logout counters, and Frappe's real error shapes (exc_type,_server_messages,exception, captured from a v16 site).HandleMethodadds a whitelisted method,Handle("METHOD /path", h)overrides a route (ErrorHandler,HTMLPage), andRequests()returns what was sent. - CLI harness (
internal/cmd/cli_harness_test.go).fakeConfig(t, site, "apikey"|"password"|"oauth")writes a config;runFFC(t, cfg, stdin, args...)runs the root command with stdout/stderr captured and resets every flag afterwards. - MCP.
newMCPFake(t, readOnly)registers the tools against a fake site;callToolgoes through JSON-RPC so argument decoding matches a real client. - Contract tests (
internal/cmd/contract_test.go, build tagcontract). Run against a real, disposable site:make contract SITE=<ffc config site>, orFFC_CONTRACT_URLwithFFC_CONTRACT_API_KEY/_SECRETorFFC_CONTRACT_USER/_PASSWORD. Each run creates the custom submittable DocTypeFFC Contract Test(childFFC Contract Test Item, a Custom Field and a Property Setter), and removes it again, leftovers of an interrupted run included. They pin number literals (Currency alwaysx.0), the list default (nameonly), child-table PUT (replaces rows), submit/cancel/amend (frappe.client.submittakes the doc, an amendment is<name>-1, editing a submitted doc is UpdateAfterSubmitError 417), schema merging, session logout and POST without CSRF, and that the fake fails like the real site..github/workflows/contract.ymlruns them nightly against ERPNext v15 and v16 from frappe_docker's pwd.yml. - Every new command or tool ships with tests against the fake. Behaviour the fake cannot prove (real Frappe semantics) belongs in the contract tests (T1.7 layer 2).
Conventions
- Error handling: Wrap with
fmt.Errorf("context: %w", err). Never log and return; return and let caller decide. - Stdout vs stderr: Data goes to stdout, diagnostics/errors go to stderr.
- Exit codes (
exit.go, part of the CLI contract; docs/cli/exit-codes.md): 0 ok, 1 generic (also a failedffc doctorcheck, viacodeError), 2 usage, 3 auth, 4 not found, 5 permission, 6 validation/conflict, 7 network/server, 8 partial bulk, 130 interrupted.ffc cananswering "denied" isdeniedError(5, the result is still printed).classifymaps typed errors:client.APIError(status + exc_type),client.AuthError(login),client.TransportError(no response),client.StateError(document in the wrong state, 6),usageError(usageErrorffor invalid flag values; anything cobra rejects before RunE is wrapped automatically),partialError(bulk). Return these types instead of plain errors where the class matters. With--json,reportErrorprints{"error":{code,exit_code,status,exc_type,message}}on stderr. Only the config TUI's explicit "Cancel" exits 0. - No prompts without a terminal.
runFormreturnserrNoInput(a usage error) when--no-inputis set or stdin is not a TTY;confirmturns it into "pass --yes". New prompts must go throughrunForm. - Environment:
applyEnv(cobra.OnInitialize) fills--site/--config/--timeoutfromFFC_SITE/FFC_CONFIG/FFC_TIMEOUTwhen the flag is unset; an invalid value fails in the RunE wrapper (trackRunStart). - Config precedence: flags > env vars > config file > defaults.
- Auth: Bearer token for OAuth sites;
Authorization: token key:secretfor API-key sites;Cookie: sid=<sid>for username/password sites.client.New()picks the method fromcfg.AccessToken/cfg.APIKey+cfg.APISecret/cfg.IsSessionAuth(), in that order.client.New()is fallible because session sites log in inside it. - Adding a data command: create
internal/cmd/<name>.go, setArgs: cobra.NoArgs, callcallSite(cmd, title, func(ctx, c) ...), register viarootCmd.AddCommand()ininit(). Print the result withrender(v, fields, tableFn)(orif machineOutput() { return printResult(v) }before the table code), neveroutput.PrintJSONdirectly, so--output/--jqwork. Lists uselistDocsfor--all. JSON-valued flags go throughparseObject/filtersFlag/jsonFlagso@FILE/@-work. Never build a client withclient.Newdirectly in a command — usenewClient/callSiteso OAuth refresh happens. A command that writes registers--dry-runwithaddDryRunand skips its confirmation whendryRunOn(cmd). - Adding an MCP tool: use
toolHandler(env, parse); read JSON-valued params withjsonArg/rawJSONArg/objectArg(neverreq.GetString— it returns "" for a native object), integers withintArg. Add the tool totoolActionsin mcp_policy.go (read, write or method; its read-only annotation must match,TestMCPPolicyCoversEveryToolchecks both) and totoolSurface(tool set, title,big;TestMCPToolSurface), and teachscopeOfany argument that names DocTypes or documents. registerTools drops the tools the policy (read_only, allow_tools) does not allow.
Config
Default config path: ~/.config/ffc/config.yaml (dir 0700, file 0600, lock file config.yaml.lock).
Env vars:
FFC_API_KEY+FFC_API_SECRET— only honoured as a pair; they then replace every stored credential of the selected site.FFC_URL— applies only together with that pair (never redirects stored credentials to another host);FFC_URLalone that differs from the site URL is an error, so a script aimed at another host never runs against the stored one. With no config file at the default path, the three env vars alone define the site.FFC_NO_UPDATE_CHECK=1— disables the background update check.FFC_OAUTH_CLIENT_SECRET— secret of the OAuth Client given with--client-id(setup only,setupFlags.oauthClient; stored asoauth_client_secret); ignored with a warning without--client-id.
Common Pitfalls
- The
config.yamlin the project root is gitignored — it's for local dev only. Do not commit credentials. - All config writes go through
config.Edit(orconfig.Overwritefor a fresh file). They takeconfig.yaml.lock, re-read the file, apply the callback to aconfig.File(yaml.Node tree: keeps comments and key order), and write atomically at 0600, following symlinks. Returnconfig.ErrUnchangedfrom the callback to skip the write. Any network call made while holding the lock must be bounded byconfig.MaxLockHold(30 s; the lock is considered stale after 3×), and release removes the lock only if it still holds this process's token. Never write config.yaml withos.WriteFileor by marshalling the struct. - Site names keep their case and may contain dots (
Prod,erp.example.com).--site/default_sitematch exactly first, then fall back to a unique case-insensitive match (what viper users relied on). viper was removed because it lowercased keys and split them on dots; do not reintroduce it.Config/SiteConfigcarryyamltags only. - Response JSON is decoded with
UseNumber, so numbers arrive asjson.Number(exact large ints,0.0stays0.0in--json). Code that inspects a numeric value must handlejson.Number(seenumericin get_schema.go);output.formatValueprints integer literals as-is and formats the rest with the number format. Trailing data after the JSON body is an error. - Frappe API wraps list results in
"data"(v14+) or"message"(older). The client handles both. A 2xx single-document response withoutdatais an error, not an empty doc. - Reading, creating or updating a document of a DocType that does not exist is a 500
ImportError("No module named 'frappe.core.doctype.x'"), not a 404; GetDoc/CreateDoc/UpdateDoc then probe the DocType's list (missingDocType; a 404 there means no DocType record), setAPIError.MissingDocType, andclassifymakes it not found (exit 4). The message cannot be trusted: sites that hide tracebacks send none. Listing and deleting give a real 404. The fake and the contract tests pin both. - Frappe error responses contain nested JSON strings with Python tracebacks.
frappeErrorResponse.userMessage()extracts the user-facing message; non-JSON error bodies are cut to 300 runes and sanitised. - Redirects: only GET/HEAD follow redirects. A redirected POST/PUT/DELETE fails with the target URL, because Go would otherwise replay it as a body-less GET and report success (e.g. delete-doc against an
http://URL that redirects tohttps://). A followed redirect never goes from https to http, and a request carryingAuthorizationorCookieis never redirected to another host name (Go would copy them to a subdomain); both fail with a*client.RedirectError. - Non-site HTTP (GitHub release API, downloads) uses
client.NewHTTPClient(timeout), neverresty.New()— resty's default logger printsWARN RESTYlines on stderr. - Retries: only GET, on 429/502/503/504 and on transport errors, never after a timeout or cancel, a refused redirect or a TLS/certificate error (
retryableTransport). A Retry-After up to 10 s (maxRetryAfter) is honoured; a longer one is reported instead of retried. Do not add retries to writes. - Username/password (session-cookie) auth has no
sidin config. CLI commands log in once per invocation and log out when they finish (callSite,bulkFlags.runandpingdeferc.CloseQuietly(), which POSTs/api/method/logoutwith a fresh 5 s context); without that, every run left a live session in theSessionstable. A command that builds its own client must do the same. Long-lived users of one client (MCP daemon, bulk runs) rely onFrappeClient.relogin: on a 401/403 with a session older than 1 minute it first asksfrappe.auth.get_logged_userwhether the session is still valid (then it is a real permission error, no new login), and logins are single-flight underloginMu, keyed by the sid each request used.Close(ctx)logs out; the MCP provider drops a replaced client without logging out (in-flight calls may still use it). Do not persist asidto config. - The plaintext
passwordfield inSiteConfigis stored at 0600 — same protection asapi_secret. ffc has no OS-keychain integration. - In huh v1.0.0, only
ctrl+cis bound to Quit by default. UserunForm(auth_wizard.go), which adds Escape viaescQuitKeyMap()and maps an abort toerrAborted. update_check.gosetsrootCmd.PersistentPreRunEin itsinit(). Do not set it anywhere else — it would silently overwrite the hook.- The update check is skipped for
update,mcp(and subcommands),completion,__completeandhelp, and whenFFC_NO_UPDATE_CHECKis set.checked_atis recorded before the fetch, so a failing network costs at most one attempt per day. State file:~/.config/ffc/.update_check.json(0600). - OAuth PKCE: the callback server binds
127.0.0.1(the redirect URI ishttp://127.0.0.1:<port>/callback, notlocalhost) before the form opens, accepts exactly one result, answers duplicates with 409, and is always closed on abort. IsOAuth()returns true only ifAccessToken != "".IsSessionAuth()requires bothUsernameandPassword.client.LoginPassworddoes not support Frappe 2FA; it returns an error pointing to OAuth or an API key.SiteConfig.Nameis a runtime-only field (yaml:"-") set byconfig.Loadto the exact YAML key; token writes use it as the site key.-ois local only:list-docs --order-by, and--output-fileofdownload,pdf,exportandimport-template. The output format flag is--outputwith no shorthand (a persistent-owould panic on the shorthand clash). Never make-opersistent.--output jsonmust stay byte-identical to the old--json(indented, HTML-escaped by encoding/json). YAML numbers go throughyamlNode(yaml.v3 would quote a json.Number).ffc apidefaults to GET even with fields (gh switches to POST): a bare-fon/api/resource/Xwould create a document. Only--inputimplies POST.SitePathrefuses absolute and//hostURLs;CheckHeaders/RawrefuseAuthorization,Cookie,Host,X-Frappe-Site-NameandX-Forwarded-Host(the last three route to another site on a bench). Keep both checks in the client: they are the credential boundary.- MCP stdout is the JSON-RPC channel. Tool handlers must never write to stdout or call
output.Print*. Return results viamarshalResult/mcp.NewToolResultTextand errors viamcp.NewToolResultErrorwith a nil Go error. Stderr is safe in stdio mode (clients log it) and ismcp.login detached mode — never print secrets there (the daemon prints its bearer token only to a terminal;ffc mcp statusshows it). --dry-runis per command (addDryRun), not global; MCP never dry-runs. The context mark is set in thetrackRunStartwrapper, andclient.sendreturns a*client.DryRunErrorinstead of sending: scope "writes" holds back everything but GET/HEAD (reads run, so state errors still surface), scope "all" (call-method, api) holds back everything. The error stops the command at its first write;executeprints the plan and exits 0. A new write command must calladdDryRunand skip its confirmation whendryRunOn(cmd). Login/logout use their own resty clients and still run, and so does an OAuth refresh inloadSite(reads need a valid token).--debugsetsclient.DebuginapplyEnv(resolveDebug), so it applies to clients built afterwards; the spinner is off while tracing, and the detached MCP child gets--debug=<level>. Any new place that logs requests or plans must use the redaction helpers in debug.go;TestDebugNeverPrintsSecretscovers all three auth methods.- The stdio server uses
server.NewStdioServer(s).Listen(cmd.Context(), …). Do not go back toServeStdiowith a context func returningcmd.Context(): that dropped the session mcp-go puts in the context (client name, capabilities, elicitation). mcp_detach_unix.go/mcp_detach_windows.gouse build tags. Keepsyscall/golang.org/x/sys/windowsfields out of untagged files.get-schema --jsonreturns a compact view by default (compactSchemain get_schema.go);--fullgives the raw response,--keysfilters top-level keys.fetchSchemais shared by the CLI and MCP: it merges Custom Fields (mergeCustomFields, byinsert_after) and then applies every Property Setter (applyPropertySetters: DocField and DocType level, values cast byproperty_typeto json.Number like every number the site sends,field_orderreorders fields). Problems become warnings (_warningsin CLI JSON), not failures. A 403 on the DocType record (every user without System Manager, also for a DocType that does not exist) falls back toclient.DeskMeta(getdoctype: customizations applied,__keys dropped); a 403 there too keeps the first error.get-docandupdate-docdefault--nameto the DocType name (Single DocTypes);delete-dockeeps--namerequired.update-docstrips anamekey from--datawith a warning (the name comes from the URL).list-docs --limit 0means no limit; negative--limit/--startare rejected.--filtersmust be a JSON object or array.go.modhasgo 1.26.0andtoolchain go1.27.3. CI and GoReleaser install Go fromgo-version-file: go.mod, which can resolve to thegoline; the toolchain line guarantees the patched release either way (setup-go orGOTOOLCHAIN=autoswitches to it). Without it, release binaries were once built with Go 1.25.0 and carried 30 reachable stdlib vulnerabilities. Bump the toolchain with each Go patch release and rungovulncheck ./....- Go 1.25 is end of life, so the
goline moved to 1.26 andgolang.org/x/*is no longer pinned to old versions. Keep thegoline one release behind the toolchain (it is the minimum users building from source need); move it only when a dependency requires it. - mcp-go v1.x speaks MCP protocol 2026-07-28 and every earlier revision, chosen per request; tool registration is unchanged. Input-schema validation (
server.WithInputSchemaValidation) stays off: the arg helpers in mcp_args.go accept numeric strings and JSON-encoded strings that a strict schema would reject.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

