Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@ All notable changes to this project will be documented in this file.

## [Unreleased]

### Added

- `chatter_post` accepts an optional `subject`. Without one, Odoo titles the
notification email with the record name (for example `INV/2026/00036`).
The subject is plain text on one line, at most 200 characters: line breaks
and control characters become spaces, which also prevents email header
injection. It is not HTML-escaped, because `mail.message.subject` is a
plain-text field that Odoo escapes when displaying it. The subject is part
of the approval payload, so changing or dropping it invalidates the token.

## [1.3.2] - 2026-08-19

### Changed
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ Once configured (see [Setup](#setup)), ask your agent things like:
| Streamable HTTP | Local HTTP/SSE support for clients that do not use stdio. |
| Smart field selection | `search_records` and `read_record` curate business-relevant fields when no `fields` argument is supplied — drops audit, message, binary, and unstored compute noise. Pass `fields=["*"]` to opt out. |
| Server-side aggregation | `aggregate_records` pushes groupby/sum/count/avg into Postgres via `formatted_read_group` (Odoo 19+) or `read_group` (16-18). |
| Chatter integration | `chatter_post` adds messages to any `mail.thread` record under the same approval-token gate as writes — or directly via `MCP_CHATTER_DIRECT=1`. |
| Chatter integration | `chatter_post` adds messages (with an optional one-line `subject`) to any `mail.thread` record under the same approval-token gate as writes — or directly via `MCP_CHATTER_DIRECT=1`. |
| Locale plumbing | `ODOO_LOCALE` injects `context.lang` automatically on every Odoo call (caller can override). |
| Structured logging | JSON formatter and rotating file handler via `ODOO_MCP_LOG_LEVEL`, `ODOO_MCP_LOG_JSON`, `ODOO_MCP_LOG_FILE`. |
| Safe writes | Direct `create`, `write`, and `unlink` are blocked; approved writes require live metadata, a same-session token, explicit confirmation, and an env gate. |
Expand Down
12 changes: 11 additions & 1 deletion scripts/odoo_compose_smoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -1154,13 +1154,15 @@ async def mcp_stdio_smoke(
)

chatter_body = "Smoke chatter execute round-trip"
chatter_subject = f"Smoke subject {transport} A & <b>B</b>"
chatter_preview = decode_tool_json(
await session.call_tool(
"chatter_post",
arguments={
"model": "res.partner",
"record_id": 1,
"body": chatter_body,
"subject": chatter_subject,
},
),
"chatter_post",
Expand All @@ -1183,6 +1185,7 @@ async def mcp_stdio_smoke(
"model": "res.partner",
"record_id": 1,
"body": chatter_body,
"subject": chatter_subject,
"approval": chatter_preview["approval"],
"confirm": True,
},
Expand All @@ -1206,8 +1209,9 @@ async def mcp_stdio_smoke(
["model", "=", "res.partner"],
["res_id", "=", 1],
["body", "ilike", "round-trip"],
["subject", "=", chatter_subject],
],
"fields": ["id", "body"],
"fields": ["id", "body", "subject"],
"limit": 5,
},
),
Expand All @@ -1217,6 +1221,12 @@ async def mcp_stdio_smoke(
raise AssertionError(
f"chatter_post execute did not persist a mail.message: {chatter_persisted}"
)
stored_subject = (chatter_persisted.get("result") or [{}])[0].get("subject")
# Plain-text Char: stored verbatim, not HTML-escaped.
if stored_subject != chatter_subject:
raise AssertionError(
f"chatter_post subject not stored verbatim: {stored_subject!r}"
)

return {
"transport": transport,
Expand Down
46 changes: 45 additions & 1 deletion src/odoo_mcp/tools_write.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import json
import os
import stat
import unicodedata
import xmlrpc.client
from pathlib import Path
from typing import Annotated, Any, Dict, List, Optional
Expand Down Expand Up @@ -522,6 +523,35 @@ def _execute_approved_write_gated(
return {"success": False, "tool": "execute_approved_write", "error": str(e)}


MAX_CHATTER_SUBJECT_LENGTH = 200


def _normalize_chatter_subject(subject: Optional[str]) -> Optional[str]:
"""Return a one-line plain-text subject, or None when blank.

``mail.message.subject`` is a Char field: Odoo escapes it when rendering
the chatter and uses it as the email ``Subject`` header, so it is not
HTML-escaped here (that would show ``&amp;`` to recipients). Line breaks
and other control characters become spaces, which also rules out header
injection; whitespace runs collapse to one space.
"""
if subject is None:
return None
flattened = "".join(
" " if unicodedata.category(ch) in {"Cc", "Zl", "Zp"} else ch
for ch in str(subject)
)
normalized = " ".join(flattened.split())
if not normalized:
return None
if len(normalized) > MAX_CHATTER_SUBJECT_LENGTH:
raise ValueError(
f"subject must be at most {MAX_CHATTER_SUBJECT_LENGTH} characters "
f"(got {len(normalized)})."
)
return normalized


def _build_chatter_payload(
*,
model: str,
Expand All @@ -532,9 +562,13 @@ def _build_chatter_payload(
partner_ids: Optional[List[int]],
attachment_ids: Optional[List[int]],
instance: str = "default",
subject: Optional[str] = None,
) -> Dict[str, Any]:
"""Build the canonical message_post call payload (deterministic ordering)."""
kwargs: Dict[str, Any] = {"body": body, "message_type": message_type}
if subject:
# Only present when set, so tokens for subject-less posts are unchanged.
kwargs["subject"] = subject
if subtype_xmlid:
kwargs["subtype_xmlid"] = subtype_xmlid
if partner_ids:
Expand All @@ -552,7 +586,8 @@ def _build_chatter_payload(

@mcp.tool(
description=(
"Post a chatter message on a mail.thread record. Default mode requires "
"Post a chatter message, with an optional one-line subject, on a "
"mail.thread record. Default mode requires "
"an approval token returned from a preview call; set MCP_CHATTER_DIRECT=1 "
"to bypass and post immediately."
),
Expand All @@ -571,6 +606,7 @@ def chatter_post(
approval: Optional[Dict[str, Any]] = None,
confirm: bool = False,
instance: Optional[str] = None,
subject: Optional[str] = None,
) -> Dict[str, Any]:
"""Post a message on the chatter of a mail.thread-derived record.

Expand All @@ -581,6 +617,12 @@ def chatter_post(
- Direct (``MCP_CHATTER_DIRECT=1``): the message is posted on the first
call without a token.

``subject`` (optional) is plain text on one line, at most 200 characters;
line breaks and control characters become spaces. Odoo uses it as the
email subject instead of the record name. ``partner_ids`` sets the
recipients notified for a ``comment``; followers of the subtype are
notified too, as in the Odoo UI. The approval token covers the subject.

Allowed ``message_type`` values: ``comment`` (default), ``notification``.
"""
try:
Expand All @@ -593,6 +635,7 @@ def chatter_post(
raise ValueError("body must be a non-empty string")
if message_type not in {"comment", "notification"}:
raise ValueError("message_type must be 'comment' or 'notification'.")
subject_text = _normalize_chatter_subject(subject)

canonical = _build_chatter_payload(
model=model,
Expand All @@ -603,6 +646,7 @@ def chatter_post(
partner_ids=partner_ids,
attachment_ids=attachment_ids,
instance=instance_name,
subject=subject_text,
)
token = build_approval_token(canonical)

Expand Down
164 changes: 164 additions & 0 deletions tests/test_chatter_subject.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
"""chatter_post accepts an optional one-line, plain-text subject.

Without a subject Odoo titles the notification email with the record name.
The subject is part of the canonical payload, so the approval token covers it.
"""

import importlib


class FakeRequest:
def __init__(self, lifespan_context):
self.lifespan_context = lifespan_context


class FakeLife:
def __init__(self, odoo):
self.odoo = odoo
self.schema_cache = {}
self.write_approvals = {}

def get_client(self, instance=None):
return "default", self.odoo


class FakeCtx:
def __init__(self, odoo):
self.request_context = FakeRequest(FakeLife(odoo))


class ChatterClient:
def __init__(self):
self.calls = []

def execute_method(self, model, method, *args, **kwargs):
self.calls.append((model, method, args, kwargs))
return 4242


def _server():
return importlib.import_module("odoo_mcp.server")


def _preview(client, **arguments):
return _server().chatter_post(
FakeCtx(client), model="account.move", record_id=36, body="Hola", **arguments
)


def test_without_subject_payload_and_call_have_no_subject(monkeypatch):
monkeypatch.setenv("MCP_CHATTER_DIRECT", "1")
client = ChatterClient()

result = _preview(client)

assert result["success"] is True
assert "subject" not in client.calls[0][3]


def test_subject_is_passed_to_message_post_with_recipients(monkeypatch):
monkeypatch.setenv("MCP_CHATTER_DIRECT", "1")
client = ChatterClient()

result = _preview(
client,
subject="Factura INV/2026/00036",
subtype_xmlid="mail.mt_comment",
partner_ids=[15],
)

assert result["success"] is True
model, method, args, kwargs = client.calls[0]
assert (model, method, args) == ("account.move", "message_post", ([36],))
assert kwargs["subject"] == "Factura INV/2026/00036"
assert kwargs["message_type"] == "comment"
assert kwargs["subtype_xmlid"] == "mail.mt_comment"
assert kwargs["partner_ids"] == [15]


def test_subject_is_flattened_to_one_line_and_kept_as_plain_text(monkeypatch):
monkeypatch.delenv("MCP_CHATTER_DIRECT", raising=False)

preview = _preview(
ChatterClient(),
subject=" Factura\r\nBcc: x@evil.example\t<b>A & B</b>
fin\x00 ",
)

subject = preview["approval"]["kwargs"]["subject"]
assert subject == "Factura Bcc: x@evil.example <b>A & B</b> fin"
assert "\n" not in subject and "\r" not in subject
# Char field: Odoo escapes it at render time; no HTML entities added here.
assert "&amp;" not in subject


def test_blank_subject_is_treated_as_absent(monkeypatch):
monkeypatch.delenv("MCP_CHATTER_DIRECT", raising=False)

with_blank = _preview(ChatterClient(), subject=" \n\t ")
without = _preview(ChatterClient())

assert "subject" not in with_blank["approval"]["kwargs"]
assert with_blank["approval"]["token"] == without["approval"]["token"]


def test_subject_over_the_limit_is_rejected(monkeypatch):
monkeypatch.setenv("MCP_CHATTER_DIRECT", "1")
client = ChatterClient()
server = _server()

at_limit = _preview(client, subject="x" * server.tools_write.MAX_CHATTER_SUBJECT_LENGTH)
too_long = _preview(
client, subject="x" * (server.tools_write.MAX_CHATTER_SUBJECT_LENGTH + 1)
)

assert at_limit["success"] is True
assert too_long["success"] is False
assert "at most 200 characters" in too_long["error"]
assert len(client.calls) == 1


def test_token_covers_subject(monkeypatch):
monkeypatch.delenv("MCP_CHATTER_DIRECT", raising=False)
client = ChatterClient()
server = _server()
ctx = FakeCtx(client)

preview = server.chatter_post(
ctx, model="account.move", record_id=36, body="Hola", subject="Asunto A"
)
no_subject = server.chatter_post(ctx, model="account.move", record_id=36, body="Hola")
assert preview["approval"]["token"] != no_subject["approval"]["token"]

changed = server.chatter_post(
ctx,
model="account.move",
record_id=36,
body="Hola",
subject="Asunto B",
approval=preview["approval"],
confirm=True,
)
dropped = server.chatter_post(
ctx,
model="account.move",
record_id=36,
body="Hola",
approval=preview["approval"],
confirm=True,
)
assert changed["success"] is False
assert "does not match" in changed["error"]
assert dropped["success"] is False
assert client.calls == []

approved = server.chatter_post(
ctx,
model="account.move",
record_id=36,
body="Hola",
subject="Asunto A",
approval=preview["approval"],
confirm=True,
)
assert approved["success"] is True
assert client.calls[0][3]["subject"] == "Asunto A"