becda-mcp 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Becda
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,114 @@
1
+ Metadata-Version: 2.4
2
+ Name: becda-mcp
3
+ Version: 0.1.0
4
+ Summary: Official MCP server for Becda decision memory & Decision Rules: AI reads, Becda learns how you decide.
5
+ License: MIT
6
+ Project-URL: Homepage, https://becda.com
7
+ Project-URL: Documentation, https://becda.com/belgeler
8
+ Project-URL: Repository, https://github.com/becda/becda-mcp
9
+ Project-URL: Security, https://becda.com/guvenlik
10
+ Keywords: mcp,becda,accounting,erp,e-invoice,decision-engine
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: mcp<2,>=1.27
15
+ Dynamic: license-file
16
+
17
+ # becda-mcp
18
+
19
+ A read-only MCP server for Becda decision memory. AI reads. Becda learns how you decide.
20
+
21
+ An AI agent can ask Becda what code a record should get, how sure Becda is, and whether it is
22
+ safe to process the record automatically. The agent cannot teach, change or delete anything.
23
+
24
+ ## Install
25
+
26
+ ```
27
+ pip install becda-mcp
28
+ # or run without installing:
29
+ uvx becda-mcp
30
+ ```
31
+
32
+ Python 3.10 or newer. The only dependency is the official `mcp` SDK. The server talks to the
33
+ Becda API over HTTPS with the Python standard library.
34
+
35
+ ## Configuration (environment variables only)
36
+
37
+ | Variable | Required | Meaning |
38
+ |---|---|---|
39
+ | `BECDA_API_KEY` | yes | Your key. Use a read-only key (starts with `becda_ro_`). |
40
+ | `BECDA_TENANT` | yes | Your tenant id. Tools take no tenant parameter. |
41
+ | `BECDA_BASE_URL` | no | Default `https://api.becda.com`. Change it for a self-hosted setup. |
42
+ | `BECDA_SCHEMA` | no | Path to a schema JSON file (see below). |
43
+ | `BECDA_HASH_SALT` | no | Salt for hashed fields. Required if the schema hashes any field. |
44
+
45
+ If the key does not start with `becda_ro_`, the server prints a warning to stderr and still works.
46
+ Examples for Claude Desktop and Cursor are in `becda_mcp/ornekler/`.
47
+
48
+ ## Tools
49
+
50
+ Read-only tools (all work with a `becda_ro_...` read-only key):
51
+
52
+ - `becda_predict(fields, text?, item_id?)`: one record. Runs through the tenant's active Decision Rules (pre-rules and post-rules) and decision memory, returning the structured result (`code`, `confidence`, `auto_approved`, `reason`, plus `rule_*` fields when a rule applies) and `normalized_fields`.
53
+ - `becda_predict_batch(records)`: up to 100 records. Same shape per record.
54
+ - `becda_status()`: observation counts, cold start flag, alarm, closed codes, and active rule version (when rules are enabled).
55
+ - `becda_explain(result)`: turns a `becda_predict` result (including rule-triggered outcomes) into a few plain sentences. Runs locally; no server call.
56
+ - `becda_rules_summary()`: reads the tenant's active company/policy decision rules (pre-rules and post-rules) together with plain-English summaries. Uses no quota.
57
+ - `becda_rules_simulate(fields, text?, pre_rules?, post_rules?)`: dry-runs current or proposed rules against this tenant's real memory with zero quota cost and zero side effects.
58
+ - `becda_rules_telemetry(limit?)`: reads ZDR-safe live decision rule hit counts and recent events (never contains invoice text, supplier names, or amounts). Uses no quota.
59
+
60
+ Draft-only staging tool (requires a full write key; returns `403 read_only_key` with `becda_ro_...`):
61
+
62
+ - `becda_rules_save_draft(pre_rules?, post_rules?, enabled?)`: validates a JDM decision table (blocking arbitrary code nodes) and saves it as a **DRAFT only**. Live traffic is never changed automatically—a person reviews the plain-language summary and publishes it in the Becda Portal (**Karar Kuralları**).
63
+
64
+ There are no learn, rollback, forget, close-code, or live rule-publish tools.
65
+
66
+ ## Schema file (`becda-sema.json`)
67
+
68
+ ```
69
+ {
70
+ "fields": {
71
+ "<canonical_name>": {
72
+ "aliases": ["other_name", "..."], // matched case-insensitively
73
+ "clean": ["strip", "upper"], // applied in order
74
+ "hash": true // optional
75
+ }
76
+ },
77
+ "text_max_chars": 500, // text is cut to this length
78
+ "unknown_fields": "error" // "error" (default) or "pass"
79
+ }
80
+ ```
81
+
82
+ Cleaners: `strip`; `upper`; `lower`; `digits` (keep digits only); `number` (`"20%"` becomes `"20"`,
83
+ `"0.20"` stays `"0.20"`; no guessing, anything else is left as is).
84
+
85
+ An unknown field name returns a tool error that lists the allowed names. Nothing is sent and
86
+ nothing is dropped silently. Without a schema file, fields pass through with only whitespace
87
+ stripped, at most 50 fields and 200 characters per value.
88
+
89
+ An example is in `becda_mcp/ornekler/becda-sema.json`.
90
+
91
+ ### Hashing
92
+
93
+ With `"hash": true`, the cleaned value is replaced by `"h:"` plus the first 16 hex characters of
94
+ HMAC-SHA256 with `BECDA_HASH_SALT` as key and the value as message (UTF-8). If the schema asks for a hash and
95
+ no salt is set, the call fails with a clear error.
96
+
97
+ The ERP side must use the same salt and the same format when it teaches Becda. If the salts or
98
+ cleaning rules differ, Becda will not recognise the supplier.
99
+
100
+ ## Security model
101
+
102
+ - The server runs on your machine over stdio. There is no hosted MCP service.
103
+ - The tenant and key come only from the environment. An agent cannot ask about another tenant.
104
+ - Use a read-only key. The Becda API answers 403 `read_only_key` for any write with it.
105
+ - Tool descriptions say only what a tool does. Tool output is structured JSON and does not echo
106
+ document text beyond the normalized fields.
107
+ - The API key never appears in output or logs. Each call has a 15 second timeout.
108
+
109
+ ### Why there are no write tools
110
+
111
+ A write tool would let text inside a document (an invoice, an email) steer the agent into teaching
112
+ Becda wrong decisions. That is memory poisoning through prompt injection. Becda therefore learns
113
+ only from decisions a person confirmed in the ERP, using a full-access key that the agent never
114
+ holds. A design note for an optional, human-approved write path will follow.
@@ -0,0 +1,98 @@
1
+ # becda-mcp
2
+
3
+ A read-only MCP server for Becda decision memory. AI reads. Becda learns how you decide.
4
+
5
+ An AI agent can ask Becda what code a record should get, how sure Becda is, and whether it is
6
+ safe to process the record automatically. The agent cannot teach, change or delete anything.
7
+
8
+ ## Install
9
+
10
+ ```
11
+ pip install becda-mcp
12
+ # or run without installing:
13
+ uvx becda-mcp
14
+ ```
15
+
16
+ Python 3.10 or newer. The only dependency is the official `mcp` SDK. The server talks to the
17
+ Becda API over HTTPS with the Python standard library.
18
+
19
+ ## Configuration (environment variables only)
20
+
21
+ | Variable | Required | Meaning |
22
+ |---|---|---|
23
+ | `BECDA_API_KEY` | yes | Your key. Use a read-only key (starts with `becda_ro_`). |
24
+ | `BECDA_TENANT` | yes | Your tenant id. Tools take no tenant parameter. |
25
+ | `BECDA_BASE_URL` | no | Default `https://api.becda.com`. Change it for a self-hosted setup. |
26
+ | `BECDA_SCHEMA` | no | Path to a schema JSON file (see below). |
27
+ | `BECDA_HASH_SALT` | no | Salt for hashed fields. Required if the schema hashes any field. |
28
+
29
+ If the key does not start with `becda_ro_`, the server prints a warning to stderr and still works.
30
+ Examples for Claude Desktop and Cursor are in `becda_mcp/ornekler/`.
31
+
32
+ ## Tools
33
+
34
+ Read-only tools (all work with a `becda_ro_...` read-only key):
35
+
36
+ - `becda_predict(fields, text?, item_id?)`: one record. Runs through the tenant's active Decision Rules (pre-rules and post-rules) and decision memory, returning the structured result (`code`, `confidence`, `auto_approved`, `reason`, plus `rule_*` fields when a rule applies) and `normalized_fields`.
37
+ - `becda_predict_batch(records)`: up to 100 records. Same shape per record.
38
+ - `becda_status()`: observation counts, cold start flag, alarm, closed codes, and active rule version (when rules are enabled).
39
+ - `becda_explain(result)`: turns a `becda_predict` result (including rule-triggered outcomes) into a few plain sentences. Runs locally; no server call.
40
+ - `becda_rules_summary()`: reads the tenant's active company/policy decision rules (pre-rules and post-rules) together with plain-English summaries. Uses no quota.
41
+ - `becda_rules_simulate(fields, text?, pre_rules?, post_rules?)`: dry-runs current or proposed rules against this tenant's real memory with zero quota cost and zero side effects.
42
+ - `becda_rules_telemetry(limit?)`: reads ZDR-safe live decision rule hit counts and recent events (never contains invoice text, supplier names, or amounts). Uses no quota.
43
+
44
+ Draft-only staging tool (requires a full write key; returns `403 read_only_key` with `becda_ro_...`):
45
+
46
+ - `becda_rules_save_draft(pre_rules?, post_rules?, enabled?)`: validates a JDM decision table (blocking arbitrary code nodes) and saves it as a **DRAFT only**. Live traffic is never changed automatically—a person reviews the plain-language summary and publishes it in the Becda Portal (**Karar Kuralları**).
47
+
48
+ There are no learn, rollback, forget, close-code, or live rule-publish tools.
49
+
50
+ ## Schema file (`becda-sema.json`)
51
+
52
+ ```
53
+ {
54
+ "fields": {
55
+ "<canonical_name>": {
56
+ "aliases": ["other_name", "..."], // matched case-insensitively
57
+ "clean": ["strip", "upper"], // applied in order
58
+ "hash": true // optional
59
+ }
60
+ },
61
+ "text_max_chars": 500, // text is cut to this length
62
+ "unknown_fields": "error" // "error" (default) or "pass"
63
+ }
64
+ ```
65
+
66
+ Cleaners: `strip`; `upper`; `lower`; `digits` (keep digits only); `number` (`"20%"` becomes `"20"`,
67
+ `"0.20"` stays `"0.20"`; no guessing, anything else is left as is).
68
+
69
+ An unknown field name returns a tool error that lists the allowed names. Nothing is sent and
70
+ nothing is dropped silently. Without a schema file, fields pass through with only whitespace
71
+ stripped, at most 50 fields and 200 characters per value.
72
+
73
+ An example is in `becda_mcp/ornekler/becda-sema.json`.
74
+
75
+ ### Hashing
76
+
77
+ With `"hash": true`, the cleaned value is replaced by `"h:"` plus the first 16 hex characters of
78
+ HMAC-SHA256 with `BECDA_HASH_SALT` as key and the value as message (UTF-8). If the schema asks for a hash and
79
+ no salt is set, the call fails with a clear error.
80
+
81
+ The ERP side must use the same salt and the same format when it teaches Becda. If the salts or
82
+ cleaning rules differ, Becda will not recognise the supplier.
83
+
84
+ ## Security model
85
+
86
+ - The server runs on your machine over stdio. There is no hosted MCP service.
87
+ - The tenant and key come only from the environment. An agent cannot ask about another tenant.
88
+ - Use a read-only key. The Becda API answers 403 `read_only_key` for any write with it.
89
+ - Tool descriptions say only what a tool does. Tool output is structured JSON and does not echo
90
+ document text beyond the normalized fields.
91
+ - The API key never appears in output or logs. Each call has a 15 second timeout.
92
+
93
+ ### Why there are no write tools
94
+
95
+ A write tool would let text inside a document (an invoice, an email) steer the agent into teaching
96
+ Becda wrong decisions. That is memory poisoning through prompt injection. Becda therefore learns
97
+ only from decisions a person confirmed in the ERP, using a full-access key that the agent never
98
+ holds. A design note for an optional, human-approved write path will follow.
@@ -0,0 +1,98 @@
1
+ # becda-mcp
2
+
3
+ A read-only MCP server for Becda decision memory. AI reads. Becda learns how you decide.
4
+
5
+ An AI agent can ask Becda what code a record should get, how sure Becda is, and whether it is
6
+ safe to process the record automatically. The agent cannot teach, change or delete anything.
7
+
8
+ ## Install
9
+
10
+ ```
11
+ pip install becda-mcp
12
+ # or run without installing:
13
+ uvx becda-mcp
14
+ ```
15
+
16
+ Python 3.10 or newer. The only dependency is the official `mcp` SDK. The server talks to the
17
+ Becda API over HTTPS with the Python standard library.
18
+
19
+ ## Configuration (environment variables only)
20
+
21
+ | Variable | Required | Meaning |
22
+ |---|---|---|
23
+ | `BECDA_API_KEY` | yes | Your key. Use a read-only key (starts with `becda_ro_`). |
24
+ | `BECDA_TENANT` | yes | Your tenant id. Tools take no tenant parameter. |
25
+ | `BECDA_BASE_URL` | no | Default `https://api.becda.com`. Change it for a self-hosted setup. |
26
+ | `BECDA_SCHEMA` | no | Path to a schema JSON file (see below). |
27
+ | `BECDA_HASH_SALT` | no | Salt for hashed fields. Required if the schema hashes any field. |
28
+
29
+ If the key does not start with `becda_ro_`, the server prints a warning to stderr and still works.
30
+ Examples for Claude Desktop and Cursor are in `becda_mcp/ornekler/`.
31
+
32
+ ## Tools
33
+
34
+ Read-only tools (all work with a `becda_ro_...` read-only key):
35
+
36
+ - `becda_predict(fields, text?, item_id?)`: one record. Runs through the tenant's active Decision Rules (pre-rules and post-rules) and decision memory, returning the structured result (`code`, `confidence`, `auto_approved`, `reason`, plus `rule_*` fields when a rule applies) and `normalized_fields`.
37
+ - `becda_predict_batch(records)`: up to 100 records. Same shape per record.
38
+ - `becda_status()`: observation counts, cold start flag, alarm, closed codes, and active rule version (when rules are enabled).
39
+ - `becda_explain(result)`: turns a `becda_predict` result (including rule-triggered outcomes) into a few plain sentences. Runs locally; no server call.
40
+ - `becda_rules_summary()`: reads the tenant's active company/policy decision rules (pre-rules and post-rules) together with plain-English summaries. Uses no quota.
41
+ - `becda_rules_simulate(fields, text?, pre_rules?, post_rules?)`: dry-runs current or proposed rules against this tenant's real memory with zero quota cost and zero side effects.
42
+ - `becda_rules_telemetry(limit?)`: reads ZDR-safe live decision rule hit counts and recent events (never contains invoice text, supplier names, or amounts). Uses no quota.
43
+
44
+ Draft-only staging tool (requires a full write key; returns `403 read_only_key` with `becda_ro_...`):
45
+
46
+ - `becda_rules_save_draft(pre_rules?, post_rules?, enabled?)`: validates a JDM decision table (blocking arbitrary code nodes) and saves it as a **DRAFT only**. Live traffic is never changed automatically—a person reviews the plain-language summary and publishes it in the Becda Portal (**Karar Kuralları**).
47
+
48
+ There are no learn, rollback, forget, close-code, or live rule-publish tools.
49
+
50
+ ## Schema file (`becda-sema.json`)
51
+
52
+ ```
53
+ {
54
+ "fields": {
55
+ "<canonical_name>": {
56
+ "aliases": ["other_name", "..."], // matched case-insensitively
57
+ "clean": ["strip", "upper"], // applied in order
58
+ "hash": true // optional
59
+ }
60
+ },
61
+ "text_max_chars": 500, // text is cut to this length
62
+ "unknown_fields": "error" // "error" (default) or "pass"
63
+ }
64
+ ```
65
+
66
+ Cleaners: `strip`; `upper`; `lower`; `digits` (keep digits only); `number` (`"20%"` becomes `"20"`,
67
+ `"0.20"` stays `"0.20"`; no guessing, anything else is left as is).
68
+
69
+ An unknown field name returns a tool error that lists the allowed names. Nothing is sent and
70
+ nothing is dropped silently. Without a schema file, fields pass through with only whitespace
71
+ stripped, at most 50 fields and 200 characters per value.
72
+
73
+ An example is in `becda_mcp/ornekler/becda-sema.json`.
74
+
75
+ ### Hashing
76
+
77
+ With `"hash": true`, the cleaned value is replaced by `"h:"` plus the first 16 hex characters of
78
+ HMAC-SHA256 with `BECDA_HASH_SALT` as key and the value as message (UTF-8). If the schema asks for a hash and
79
+ no salt is set, the call fails with a clear error.
80
+
81
+ The ERP side must use the same salt and the same format when it teaches Becda. If the salts or
82
+ cleaning rules differ, Becda will not recognise the supplier.
83
+
84
+ ## Security model
85
+
86
+ - The server runs on your machine over stdio. There is no hosted MCP service.
87
+ - The tenant and key come only from the environment. An agent cannot ask about another tenant.
88
+ - Use a read-only key. The Becda API answers 403 `read_only_key` for any write with it.
89
+ - Tool descriptions say only what a tool does. Tool output is structured JSON and does not echo
90
+ document text beyond the normalized fields.
91
+ - The API key never appears in output or logs. Each call has a 15 second timeout.
92
+
93
+ ### Why there are no write tools
94
+
95
+ A write tool would let text inside a document (an invoice, an email) steer the agent into teaching
96
+ Becda wrong decisions. That is memory poisoning through prompt injection. Becda therefore learns
97
+ only from decisions a person confirmed in the ERP, using a full-access key that the agent never
98
+ holds. A design note for an optional, human-approved write path will follow.
@@ -0,0 +1,2 @@
1
+ """Becda MCP server: read-only decision memory for AI agents."""
2
+ __version__ = "0.1.0"
@@ -0,0 +1,3 @@
1
+ from .sunucu import main
2
+
3
+ main()
@@ -0,0 +1,13 @@
1
+ # Example flow: foreign invoice to ERP
2
+
3
+ 1. A foreign invoice (PDF or JSON) arrives. The AI agent reads it and extracts the fields
4
+ (supplier tax id, unit, VAT rate) and, if useful, a short line text.
5
+ 2. The agent calls `becda_predict` with those fields. The MCP server maps aliases to your
6
+ field names, cleans values, hashes the supplier id with your salt, and asks Becda.
7
+ 3. Becda returns a suggested code, `auto_approved`, and a `reason`.
8
+ 4. If `auto_approved` is true, the agent hands the record on for processing.
9
+ 5. If `auto_approved` is false, the agent shows the suggestion and the reason to a person
10
+ (`becda_explain` writes a plain sentence for that). The person confirms or corrects the
11
+ code in the ERP.
12
+ 6. The ERP, not the agent, then calls `/v2/learn` with a full-access key. That is the only
13
+ way Becda learns. The agent holds a read-only key and cannot write.
@@ -0,0 +1,9 @@
1
+ {
2
+ "fields": {
3
+ "tedarikci_vkn": {"aliases": ["supplier_tax_id", "vkn", "vendor_vat"], "clean": ["strip", "digits"], "hash": true},
4
+ "birim": {"aliases": ["unit", "uom"], "clean": ["strip", "upper"]},
5
+ "kdv_orani": {"aliases": ["vat", "vat_rate", "tax_rate"], "clean": ["strip", "number"]}
6
+ },
7
+ "text_max_chars": 500,
8
+ "unknown_fields": "error"
9
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "mcpServers": {
3
+ "becda": {
4
+ "command": "uvx",
5
+ "args": ["becda-mcp"],
6
+ "env": {
7
+ "BECDA_API_KEY": "becda_ro_REPLACE_WITH_YOUR_READ_ONLY_KEY",
8
+ "BECDA_TENANT": "REPLACE_WITH_YOUR_TENANT_ID",
9
+ "BECDA_SCHEMA": "C:\\path\\to\\becda-sema.json",
10
+ "BECDA_HASH_SALT": "REPLACE_WITH_YOUR_SHARED_SALT"
11
+ }
12
+ }
13
+ }
14
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "mcpServers": {
3
+ "becda": {
4
+ "command": "python",
5
+ "args": ["-m", "becda_mcp"],
6
+ "env": {
7
+ "BECDA_API_KEY": "becda_ro_REPLACE_WITH_YOUR_READ_ONLY_KEY",
8
+ "BECDA_TENANT": "REPLACE_WITH_YOUR_TENANT_ID",
9
+ "BECDA_SCHEMA": "/path/to/becda-sema.json",
10
+ "BECDA_HASH_SALT": "REPLACE_WITH_YOUR_SHARED_SALT"
11
+ }
12
+ }
13
+ }
14
+ }
@@ -0,0 +1,129 @@
1
+ """Input normalization for the Becda MCP server (schema file, aliases, cleaners, salted hashing)."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import hmac
6
+ import json
7
+ import re
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ MAX_FIELDS = 50
12
+ MAX_VALUE_CHARS = 200
13
+ DEFAULT_TEXT_MAX = 500
14
+ CLEANERS = ("strip", "upper", "lower", "digits", "number")
15
+
16
+
17
+ class SchemaError(ValueError):
18
+ """Raised for invalid input or schema; the message is safe to show to the agent."""
19
+
20
+
21
+ def _number(v: str) -> str:
22
+ """'20%' -> '20'; '0.20' stays '0.20'. No guessing: anything else is returned unchanged."""
23
+ s = v.strip().replace(" ", "")
24
+ if s.endswith("%"):
25
+ s = s[:-1].strip()
26
+ return s if re.fullmatch(r"[+-]?\d+([.,]\d+)?", s) else v
27
+
28
+
29
+ _CLEAN = {
30
+ "strip": lambda v: v.strip(),
31
+ "upper": lambda v: v.upper(),
32
+ "lower": lambda v: v.lower(),
33
+ "digits": lambda v: re.sub(r"\D", "", v),
34
+ "number": _number,
35
+ }
36
+
37
+
38
+ def hash_value(value: str, salt: str) -> str:
39
+ """'h:' + first 16 hex chars of HMAC-SHA256(salt, value)."""
40
+ digest = hmac.new(salt.encode("utf-8"), value.encode("utf-8"), hashlib.sha256).hexdigest()
41
+ return "h:" + digest[:16]
42
+
43
+
44
+ class Schema:
45
+ def __init__(self, spec: dict | None = None, salt: str | None = None):
46
+ self.salt = salt or None
47
+ self.fields: dict[str, dict] = {}
48
+ self.alias: dict[str, str] = {}
49
+ self.text_max = DEFAULT_TEXT_MAX
50
+ self.unknown = "error"
51
+ self.has_schema = spec is not None
52
+ if spec is None:
53
+ return
54
+ if not isinstance(spec, dict) or not isinstance(spec.get("fields"), dict):
55
+ raise SchemaError("Schema file must be a JSON object with a 'fields' object.")
56
+ for name, d in spec["fields"].items():
57
+ d = d or {}
58
+ clean = d.get("clean", ["strip"])
59
+ bad = [c for c in clean if c not in CLEANERS]
60
+ if bad:
61
+ raise SchemaError(f"Schema field '{name}' has unknown cleaners: {bad}. Allowed: {list(CLEANERS)}.")
62
+ self.fields[name] = {"clean": list(clean), "hash": bool(d.get("hash", False))}
63
+ for a in [name, *d.get("aliases", [])]:
64
+ self.alias[str(a).strip().lower()] = name
65
+ self.text_max = int(spec.get("text_max_chars", DEFAULT_TEXT_MAX))
66
+ self.unknown = spec.get("unknown_fields", "error")
67
+ if self.unknown not in ("error", "pass"):
68
+ raise SchemaError("Schema 'unknown_fields' must be 'error' or 'pass'.")
69
+
70
+ @classmethod
71
+ def load(cls, path: str | None, salt: str | None) -> "Schema":
72
+ if not path:
73
+ return cls(None, salt)
74
+ try:
75
+ spec = json.loads(Path(path).read_text(encoding="utf-8"))
76
+ except (OSError, ValueError) as e:
77
+ raise SchemaError(f"Cannot read schema file: {type(e).__name__}") from None
78
+ return cls(spec, salt)
79
+
80
+ def _scalar(self, name: str, v: Any) -> str:
81
+ if v is None:
82
+ return ""
83
+ if isinstance(v, bool):
84
+ return "true" if v else "false"
85
+ if isinstance(v, (str, int, float)):
86
+ return str(v)
87
+ raise SchemaError(f"Field '{name}' must be a string or number, not {type(v).__name__}.")
88
+
89
+ def fields_out(self, fields: Any) -> dict[str, str]:
90
+ if not isinstance(fields, dict):
91
+ raise SchemaError("'fields' must be an object of field name to value.")
92
+ if len(fields) > MAX_FIELDS:
93
+ raise SchemaError(f"At most {MAX_FIELDS} fields per record.")
94
+ out: dict[str, str] = {}
95
+ if not self.has_schema:
96
+ for k, v in fields.items():
97
+ out[str(k).strip()] = self._scalar(k, v).strip()[:MAX_VALUE_CHARS]
98
+ return out
99
+ unknown = []
100
+ for k, v in fields.items():
101
+ canon = self.alias.get(str(k).strip().lower())
102
+ if canon is None:
103
+ if self.unknown == "error":
104
+ unknown.append(str(k)[:60])
105
+ else:
106
+ out[str(k).strip()] = self._scalar(k, v).strip()[:MAX_VALUE_CHARS]
107
+ continue
108
+ val = self._scalar(k, v)
109
+ for c in self.fields[canon]["clean"]:
110
+ val = _CLEAN[c](val)
111
+ if self.fields[canon]["hash"]:
112
+ if not self.salt:
113
+ raise SchemaError(
114
+ f"Field '{canon}' must be hashed but BECDA_HASH_SALT is not set. "
115
+ "Set the same salt your ERP uses.")
116
+ val = hash_value(val, self.salt) if val else val
117
+ out[canon] = val[:MAX_VALUE_CHARS]
118
+ if unknown:
119
+ raise SchemaError(
120
+ f"Unknown field(s): {sorted(unknown)}. Allowed field names: {sorted(self.alias)}. "
121
+ "Fix the names and call again; nothing was sent.")
122
+ return out
123
+
124
+ def text_out(self, text: Any) -> str | None:
125
+ if text is None:
126
+ return None
127
+ if not isinstance(text, str):
128
+ raise SchemaError("'text' must be a string.")
129
+ return text[: self.text_max]
@@ -0,0 +1,227 @@
1
+ """Becda MCP server (stdio). Read-only by default (prediction, rule inspection, simulation, ZDR telemetry) plus draft-only rule staging."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import sys
7
+ import urllib.error
8
+ import urllib.parse
9
+ import urllib.request
10
+ from typing import Any
11
+
12
+ from mcp.server.fastmcp import FastMCP
13
+ from mcp.server.fastmcp.exceptions import ToolError
14
+
15
+ from . import __version__
16
+ from .sema import Schema, SchemaError
17
+
18
+ TIMEOUT_S = 15
19
+ BATCH_MAX = 100
20
+ ITEM_ID_MAX = 200
21
+
22
+ mcp = FastMCP("becda")
23
+ _state: dict[str, Any] = {}
24
+
25
+
26
+ def _config() -> dict[str, Any]:
27
+ """Build (once) the runtime configuration from the environment."""
28
+ if _state:
29
+ return _state
30
+ key = os.environ.get("BECDA_API_KEY", "").strip()
31
+ tenant = os.environ.get("BECDA_TENANT", "").strip()
32
+ if not key or not tenant:
33
+ raise ToolError("Becda is not configured: set BECDA_API_KEY and BECDA_TENANT.")
34
+ try:
35
+ schema = Schema.load(os.environ.get("BECDA_SCHEMA") or None, os.environ.get("BECDA_HASH_SALT") or None)
36
+ except SchemaError as e:
37
+ raise ToolError(str(e)) from None
38
+ base = os.environ.get("BECDA_BASE_URL", "https://api.becda.com").strip().rstrip("/")
39
+ _state.update(key=key, tenant=tenant, base=base, schema=schema)
40
+ return _state
41
+
42
+
43
+ def _call(method: str, path: str, body: dict | None = None) -> dict:
44
+ c = _config()
45
+ url = f"{c['base']}/v2/tenants/{urllib.parse.quote(c['tenant'], safe='')}/{path}"
46
+ data = json.dumps(body).encode("utf-8") if body is not None else None
47
+ req = urllib.request.Request(url, data=data, method=method, headers={
48
+ "Authorization": f"Bearer {c['key']}", "Content-Type": "application/json", "User-Agent": "becda-mcp/0.1",
49
+ "X-Becda-Client": f"mcp/{__version__}"})
50
+ try:
51
+ with urllib.request.urlopen(req, timeout=TIMEOUT_S) as r:
52
+ return json.loads(r.read())
53
+ except urllib.error.HTTPError as e:
54
+ try:
55
+ err = json.loads(e.read() or b"{}").get("error", {})
56
+ except ValueError:
57
+ err = {}
58
+ raise ToolError(f"Becda API error {e.code} ({err.get('code', 'unknown')}): "
59
+ f"{err.get('message', 'request failed')}") from None
60
+ except (urllib.error.URLError, TimeoutError, OSError):
61
+ raise ToolError("Cannot reach the Becda API (network error or timeout). Try again later.") from None
62
+ except ValueError:
63
+ raise ToolError("The Becda API returned an invalid response.") from None
64
+
65
+
66
+ def _record(fields: Any, text: Any, item_id: Any) -> tuple[dict, dict]:
67
+ s: Schema = _config()["schema"]
68
+ try:
69
+ norm = s.fields_out(fields)
70
+ body: dict[str, Any] = {"fields": norm}
71
+ t = s.text_out(text)
72
+ if t:
73
+ body["text"] = t
74
+ if item_id is not None:
75
+ body["item_id"] = str(item_id)[:ITEM_ID_MAX]
76
+ except SchemaError as e:
77
+ raise ToolError(str(e)) from None
78
+ return body, norm
79
+
80
+
81
+ @mcp.tool()
82
+ def becda_predict(fields: dict, text: str | None = None, item_id: str | None = None) -> dict:
83
+ """Look up the decision memory for one record. Returns the suggested code, confidence, whether it is
84
+ auto-approved, a reason, and the normalized fields that were sent."""
85
+ body, norm = _record(fields, text, item_id)
86
+ res = _call("POST", "predict", body)
87
+ res["normalized_fields"] = norm
88
+ return res
89
+
90
+
91
+ @mcp.tool()
92
+ def becda_predict_batch(records: list[dict]) -> dict:
93
+ """Look up the decision memory for up to 100 records. Each record has the keys fields, text (optional) and
94
+ item_id (optional). Returns one result per record plus the normalized fields of each record."""
95
+ if not isinstance(records, list) or not records:
96
+ raise ToolError("'records' must be a non-empty list.")
97
+ if len(records) > BATCH_MAX:
98
+ raise ToolError(f"At most {BATCH_MAX} records per call.")
99
+ bodies, norms = [], []
100
+ for i, r in enumerate(records):
101
+ if not isinstance(r, dict):
102
+ raise ToolError(f"Record {i} must be an object.")
103
+ try:
104
+ b, n = _record(r.get("fields"), r.get("text"), r.get("item_id"))
105
+ except ToolError as e:
106
+ raise ToolError(f"Record {i}: {e}") from None
107
+ bodies.append(b)
108
+ norms.append(n)
109
+ res = _call("POST", "predict-batch", {"records": bodies})
110
+ res["normalized_fields"] = norms
111
+ return res
112
+
113
+
114
+ @mcp.tool()
115
+ def becda_status() -> dict:
116
+ """Show the memory state of the configured tenant: observation counts, cold start flag, alarm and closed codes."""
117
+ return _call("GET", "status")
118
+
119
+
120
+ @mcp.tool()
121
+ def becda_explain(result: dict) -> str:
122
+ """Turn one becda_predict result into a short plain-English explanation for a person. Runs locally."""
123
+ if not isinstance(result, dict):
124
+ raise ToolError("'result' must be a becda_predict result object.")
125
+ code = result.get("code")
126
+ reason = str(result.get("reason") or "no reason was given")[:300]
127
+ if result.get("rule_applied") is True:
128
+ stage = str(result.get("rule_stage") or "pre")
129
+ action = str(result.get("rule_action") or "human_review")
130
+ row = result.get("rule_row")
131
+ row_txt = f" row #{row}" if row is not None else ""
132
+ if action == "override":
133
+ return f"A tenant {stage}-rule ({row_txt.strip() or 'hard rule'}) locked code {str(code)[:40]} automatically. Reason: {reason}"
134
+ if action == "reject":
135
+ return f"A tenant {stage}-rule ({row_txt.strip() or 'hard rule'}) rejected this record. Reason: {reason}"
136
+ sug = f" Suggested code: {str(code)[:40]}." if code not in (None, "") else ""
137
+ return f"A tenant {stage}-rule ({row_txt.strip() or 'hard rule'}) routed this record to human review.{sug} Reason: {reason}"
138
+ if code in (None, ""):
139
+ lines = ["Becda has no code to suggest for this record."]
140
+ else:
141
+ lines = [f"Becda suggests code {str(code)[:40]}."]
142
+ conf = result.get("confidence")
143
+ if isinstance(conf, (int, float)) and not isinstance(conf, bool):
144
+ lines[0] = lines[0][:-1] + f" (confidence {conf:.2f})."
145
+ if result.get("auto_approved") is True:
146
+ lines.append("It is safe to process this record automatically.")
147
+ lines.append(f"Reason: {reason}")
148
+ else:
149
+ lines.append("It is not approved for automatic processing.")
150
+ lines.append(f"Reason: {reason}")
151
+ lines.append("A person must confirm the code before the record is processed.")
152
+ return " ".join(lines)
153
+
154
+
155
+ @mcp.tool()
156
+ def becda_rules_summary() -> dict:
157
+ """Read the tenant's active company and policy decision rules (pre-rules and post-rules) together with plain-English summaries. Safe with read-only keys."""
158
+ return _call("GET", "rules")
159
+
160
+
161
+ @mcp.tool()
162
+ def becda_rules_simulate(
163
+ fields: dict,
164
+ text: str | None = None,
165
+ pre_rules: dict | None = None,
166
+ post_rules: dict | None = None,
167
+ ) -> dict:
168
+ """Dry-run current or proposed pre/post decision rules against this tenant's real memory with zero quota cost and zero side effects. Safe with read-only keys."""
169
+ body, norm = _record(fields, text, None)
170
+ if pre_rules is not None:
171
+ body["pre_rules"] = pre_rules
172
+ if post_rules is not None:
173
+ body["post_rules"] = post_rules
174
+ res = _call("POST", "rules/test", body)
175
+ res["normalized_fields"] = norm
176
+ return res
177
+
178
+
179
+ @mcp.tool()
180
+ def becda_rules_telemetry(limit: int = 20) -> dict:
181
+ """Inspect ZDR-safe live decision rule hit counts and the latest recent events (never contains invoice content, supplier names or amounts). Safe with read-only keys."""
182
+ lim = max(1, min(int(limit), 100))
183
+ return _call("GET", f"rules-telemetry?limit={lim}")
184
+
185
+
186
+ @mcp.tool()
187
+ def becda_rules_save_draft(
188
+ pre_rules: dict | None = None,
189
+ post_rules: dict | None = None,
190
+ enabled: bool = True,
191
+ ) -> dict:
192
+ """Save a validated JDM decision table as a DRAFT only (never publishes to live traffic). Requires a full write key; a person must review and publish it in the Becda Portal."""
193
+ return _call("POST", "rules/draft", {
194
+ "pre_rules": pre_rules,
195
+ "post_rules": post_rules,
196
+ "enabled": bool(enabled),
197
+ })
198
+
199
+
200
+ def main() -> None:
201
+ key = os.environ.get("BECDA_API_KEY", "")
202
+ if key and not key.startswith("becda_ro_"):
203
+ print("becda-mcp: full-access key used; prefer a read-only key (becda_ro_...).", file=sys.stderr)
204
+ if not key or not os.environ.get("BECDA_TENANT"):
205
+ print("becda-mcp: BECDA_API_KEY and BECDA_TENANT must be set.", file=sys.stderr)
206
+ raise SystemExit(2)
207
+ try:
208
+ _config()
209
+ except ToolError as e:
210
+ print(f"becda-mcp: {e}", file=sys.stderr)
211
+ raise SystemExit(2)
212
+ # Açılış kontrolü: anahtar bu kiracıya mı bağlı, salt okunur mu (sunucu söyler). Ağ yoksa yalnız uyarı.
213
+ try:
214
+ kim = _call("GET", "whoami")
215
+ if not kim.get("read_only"):
216
+ print("becda-mcp: the server reports a full-access key; prefer a read-only key (becda_ro_...).",
217
+ file=sys.stderr)
218
+ except ToolError as e:
219
+ if "error 401" in str(e) or "error 403" in str(e):
220
+ print(f"becda-mcp: {e}", file=sys.stderr)
221
+ raise SystemExit(2)
222
+ print(f"becda-mcp: startup check skipped: {e}", file=sys.stderr)
223
+ mcp.run(transport="stdio")
224
+
225
+
226
+ if __name__ == "__main__":
227
+ main()
@@ -0,0 +1,114 @@
1
+ Metadata-Version: 2.4
2
+ Name: becda-mcp
3
+ Version: 0.1.0
4
+ Summary: Official MCP server for Becda decision memory & Decision Rules: AI reads, Becda learns how you decide.
5
+ License: MIT
6
+ Project-URL: Homepage, https://becda.com
7
+ Project-URL: Documentation, https://becda.com/belgeler
8
+ Project-URL: Repository, https://github.com/becda/becda-mcp
9
+ Project-URL: Security, https://becda.com/guvenlik
10
+ Keywords: mcp,becda,accounting,erp,e-invoice,decision-engine
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: mcp<2,>=1.27
15
+ Dynamic: license-file
16
+
17
+ # becda-mcp
18
+
19
+ A read-only MCP server for Becda decision memory. AI reads. Becda learns how you decide.
20
+
21
+ An AI agent can ask Becda what code a record should get, how sure Becda is, and whether it is
22
+ safe to process the record automatically. The agent cannot teach, change or delete anything.
23
+
24
+ ## Install
25
+
26
+ ```
27
+ pip install becda-mcp
28
+ # or run without installing:
29
+ uvx becda-mcp
30
+ ```
31
+
32
+ Python 3.10 or newer. The only dependency is the official `mcp` SDK. The server talks to the
33
+ Becda API over HTTPS with the Python standard library.
34
+
35
+ ## Configuration (environment variables only)
36
+
37
+ | Variable | Required | Meaning |
38
+ |---|---|---|
39
+ | `BECDA_API_KEY` | yes | Your key. Use a read-only key (starts with `becda_ro_`). |
40
+ | `BECDA_TENANT` | yes | Your tenant id. Tools take no tenant parameter. |
41
+ | `BECDA_BASE_URL` | no | Default `https://api.becda.com`. Change it for a self-hosted setup. |
42
+ | `BECDA_SCHEMA` | no | Path to a schema JSON file (see below). |
43
+ | `BECDA_HASH_SALT` | no | Salt for hashed fields. Required if the schema hashes any field. |
44
+
45
+ If the key does not start with `becda_ro_`, the server prints a warning to stderr and still works.
46
+ Examples for Claude Desktop and Cursor are in `becda_mcp/ornekler/`.
47
+
48
+ ## Tools
49
+
50
+ Read-only tools (all work with a `becda_ro_...` read-only key):
51
+
52
+ - `becda_predict(fields, text?, item_id?)`: one record. Runs through the tenant's active Decision Rules (pre-rules and post-rules) and decision memory, returning the structured result (`code`, `confidence`, `auto_approved`, `reason`, plus `rule_*` fields when a rule applies) and `normalized_fields`.
53
+ - `becda_predict_batch(records)`: up to 100 records. Same shape per record.
54
+ - `becda_status()`: observation counts, cold start flag, alarm, closed codes, and active rule version (when rules are enabled).
55
+ - `becda_explain(result)`: turns a `becda_predict` result (including rule-triggered outcomes) into a few plain sentences. Runs locally; no server call.
56
+ - `becda_rules_summary()`: reads the tenant's active company/policy decision rules (pre-rules and post-rules) together with plain-English summaries. Uses no quota.
57
+ - `becda_rules_simulate(fields, text?, pre_rules?, post_rules?)`: dry-runs current or proposed rules against this tenant's real memory with zero quota cost and zero side effects.
58
+ - `becda_rules_telemetry(limit?)`: reads ZDR-safe live decision rule hit counts and recent events (never contains invoice text, supplier names, or amounts). Uses no quota.
59
+
60
+ Draft-only staging tool (requires a full write key; returns `403 read_only_key` with `becda_ro_...`):
61
+
62
+ - `becda_rules_save_draft(pre_rules?, post_rules?, enabled?)`: validates a JDM decision table (blocking arbitrary code nodes) and saves it as a **DRAFT only**. Live traffic is never changed automatically—a person reviews the plain-language summary and publishes it in the Becda Portal (**Karar Kuralları**).
63
+
64
+ There are no learn, rollback, forget, close-code, or live rule-publish tools.
65
+
66
+ ## Schema file (`becda-sema.json`)
67
+
68
+ ```
69
+ {
70
+ "fields": {
71
+ "<canonical_name>": {
72
+ "aliases": ["other_name", "..."], // matched case-insensitively
73
+ "clean": ["strip", "upper"], // applied in order
74
+ "hash": true // optional
75
+ }
76
+ },
77
+ "text_max_chars": 500, // text is cut to this length
78
+ "unknown_fields": "error" // "error" (default) or "pass"
79
+ }
80
+ ```
81
+
82
+ Cleaners: `strip`; `upper`; `lower`; `digits` (keep digits only); `number` (`"20%"` becomes `"20"`,
83
+ `"0.20"` stays `"0.20"`; no guessing, anything else is left as is).
84
+
85
+ An unknown field name returns a tool error that lists the allowed names. Nothing is sent and
86
+ nothing is dropped silently. Without a schema file, fields pass through with only whitespace
87
+ stripped, at most 50 fields and 200 characters per value.
88
+
89
+ An example is in `becda_mcp/ornekler/becda-sema.json`.
90
+
91
+ ### Hashing
92
+
93
+ With `"hash": true`, the cleaned value is replaced by `"h:"` plus the first 16 hex characters of
94
+ HMAC-SHA256 with `BECDA_HASH_SALT` as key and the value as message (UTF-8). If the schema asks for a hash and
95
+ no salt is set, the call fails with a clear error.
96
+
97
+ The ERP side must use the same salt and the same format when it teaches Becda. If the salts or
98
+ cleaning rules differ, Becda will not recognise the supplier.
99
+
100
+ ## Security model
101
+
102
+ - The server runs on your machine over stdio. There is no hosted MCP service.
103
+ - The tenant and key come only from the environment. An agent cannot ask about another tenant.
104
+ - Use a read-only key. The Becda API answers 403 `read_only_key` for any write with it.
105
+ - Tool descriptions say only what a tool does. Tool output is structured JSON and does not echo
106
+ document text beyond the normalized fields.
107
+ - The API key never appears in output or logs. Each call has a 15 second timeout.
108
+
109
+ ### Why there are no write tools
110
+
111
+ A write tool would let text inside a document (an invoice, an email) steer the agent into teaching
112
+ Becda wrong decisions. That is memory poisoning through prompt injection. Becda therefore learns
113
+ only from decisions a person confirmed in the ERP, using a full-access key that the agent never
114
+ holds. A design note for an optional, human-approved write path will follow.
@@ -0,0 +1,18 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ becda_mcp/README.md
5
+ becda_mcp/__init__.py
6
+ becda_mcp/__main__.py
7
+ becda_mcp/sema.py
8
+ becda_mcp/sunucu.py
9
+ becda_mcp.egg-info/PKG-INFO
10
+ becda_mcp.egg-info/SOURCES.txt
11
+ becda_mcp.egg-info/dependency_links.txt
12
+ becda_mcp.egg-info/entry_points.txt
13
+ becda_mcp.egg-info/requires.txt
14
+ becda_mcp.egg-info/top_level.txt
15
+ becda_mcp/ornekler/AKIS.md
16
+ becda_mcp/ornekler/becda-sema.json
17
+ becda_mcp/ornekler/claude_desktop_config.json
18
+ becda_mcp/ornekler/cursor_mcp.json
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ becda-mcp = becda_mcp.sunucu:main
@@ -0,0 +1 @@
1
+ mcp<2,>=1.27
@@ -0,0 +1 @@
1
+ becda_mcp
@@ -0,0 +1,28 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "becda-mcp"
7
+ version = "0.1.0"
8
+ description = "Official MCP server for Becda decision memory & Decision Rules: AI reads, Becda learns how you decide."
9
+ readme = "README.md"
10
+ license = {text = "MIT"}
11
+ requires-python = ">=3.10"
12
+ dependencies = ["mcp>=1.27,<2"]
13
+ keywords = ["mcp", "becda", "accounting", "erp", "e-invoice", "decision-engine"]
14
+
15
+ [project.urls]
16
+ Homepage = "https://becda.com"
17
+ Documentation = "https://becda.com/belgeler"
18
+ Repository = "https://github.com/becda/becda-mcp"
19
+ Security = "https://becda.com/guvenlik"
20
+
21
+ [project.scripts]
22
+ becda-mcp = "becda_mcp.sunucu:main"
23
+
24
+ [tool.setuptools]
25
+ packages = ["becda_mcp"]
26
+
27
+ [tool.setuptools.package-data]
28
+ becda_mcp = ["ornekler/*", "README.md"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+