### Calling main() with streamable-http transport Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/server.md Example usage of the main() entry point, passing CLI arguments to start the server with Streamable HTTP transport, binding to 0.0.0.0 and using a token file. ```python from amazonorders_mcp.server import main main(["--transport", "streamable-http", "--host", "0.0.0.0", "--token-file", "/run/secrets/token"]) ``` -------------------------------- ### create_http_app usage example Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/server.md Shows how to create a server and HTTP app with a token, then run it with uvicorn on 127.0.0.1:8000. ```python import uvicorn from amazonorders_mcp.server import create_server, create_http_app server = create_server() app = create_http_app(server, token="secret") uvicorn.run(app, host="127.0.0.1", port=8000) ``` -------------------------------- ### SavedSession run usage example Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/session.md Example of using the run method to get orders for a specific year and site. ```python session = SavedSession() year = session.run(lambda s: AmazonOrders(s).get_orders(year=2024), "amazon.de") ``` -------------------------------- ### Common setup: MCP client for calling tools Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/tools.md Sets up an MCP client using the `mcp` Python SDK to call tools via stdio. The `call` helper invokes a tool by name and arguments, returning the result. This is the base for all examples on the page. ```python from mcp.client import Client from mcp.client.stdio import StdioServerParameters STDIO = StdioServerParameters(command="uvx", args=["amazon-orders-mcp"]) async def call(name: str, args: dict): async with Client(STDIO) as client: return await client.call_tool(name, args) ``` -------------------------------- ### search_orders pagination example Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/tools.md Shows how to call search_orders with a cursor to fetch the next page. The first call uses a limit of 1, and the second call passes the cursor from the first result to get the next page. ```python page1 = await call("search_orders", {"query": "trowel", "limit": 1}) page2 = await call("search_orders", {"query": "trowel", "cursor": page1.structured_content["cursor"]}) print(page2.structured_content["items"][0]["item"]["title"]) ``` -------------------------------- ### get_gift_cards usage example Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/tools.md Example call to get_gift_cards with days=30, printing the balance from the structured content. ```python gc = await call("get_gift_cards", {"days": 30}) print(gc.structured_content["balance"]) ``` -------------------------------- ### get_prime_payments usage example Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/tools.md Example call to get_prime_payments with no parameters, printing the order number of the first item. ```python payments = await call("get_prime_payments", {}) print(payments.structured_content["items"][0]["order_number"]) ``` -------------------------------- ### create_http_app(server, host=DEFAULT_HOST, json_response=False, token=None) Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/server.md Builds the ASGI app that serves the MCP server over Streamable HTTP at /mcp and adds GET /health. When token is given, wraps the app in BearerTokenMiddleware. ```APIDOC ## create_http_app(server, host=DEFAULT_HOST, json_response=False, token=None) ### Description Builds the ASGI app that serves the MCP server over Streamable HTTP at `/mcp` (via `server.streamable_http_app(stateless_http=True, json_response=json_response, host=host)`), and adds `GET /health`. When `token` is given, wraps the app in `BearerTokenMiddleware`. ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `server` | `MCPServer` | yes | — | The server to serve | | `host` | `str` | no | `"127.0.0.1"` | The address the app listens on; on loopback, only requests addressed to a loopback host are accepted (DNS-rebinding protection) | | `json_response` | `bool` | no | `False` | Answer each request with JSON instead of an event stream; progress is not reported then | | `token` | `Optional[str]` | no | `None` | Bearer token every request but the health check must carry | ### Returns `ASGIApp` (`starlette.types`). ### Usage ```python import uvicorn from amazonorders_mcp.server import create_server, create_http_app server = create_server() app = create_http_app(server, token="secret") uvicorn.run(app, host="127.0.0.1", port=8000) ``` ``` -------------------------------- ### BearerTokenMiddleware usage example Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/server.md Shows how to wrap an inner app with BearerTokenMiddleware using a token. Requests without the correct Authorization header receive 401 Unauthorized with WWW-Authenticate: Bearer. ```python app = BearerTokenMiddleware(inner_app, "s3cret") # without Authorization: Bearer s3cret -> 401 Unauthorized, WWW-Authenticate: Bearer ``` -------------------------------- ### Iterator Prototype Setup Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/tests/resources/orders/order-history-2018-0.html Sets up the prototype for an iterator. ```javascript function(e,t,n){ ``` ```javascript "use strict";var r=n(95).IteratorPrototype,A=n(44),o=n(29),i=n(30),a=n(33),u=function(){return this};e.exports=function(e,t,n){var c=t+" Iterator";return e.prototype=A(r,{next:o(1,n)}),i(e,c,!1,!0),a[c]=u,e}} ``` -------------------------------- ### Run Amazon Orders MCP with Streamable HTTP Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/README.md Start the server using the streamable-http transport for remote client connections. It defaults to http://127.0.0.1:8000/mcp. ```sh uvx amazon-orders-mcp --transport streamable-http ``` -------------------------------- ### get_orders pagination example Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/tools.md Shows how to fetch the first page with year and limit, then use the returned cursor to fetch the next batch. The cursor carries over filters from the previous call. ```python first = await call("get_orders", {"year": 2024, "limit": 25}) print(len(first.structured_content["items"]), first.structured_content["has_more"]) second = await call("get_orders", {"cursor": first.structured_content["cursor"]}) ``` -------------------------------- ### sign_in example with site parameter Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/tools.md Calls `sign_in` with `site` set to `amazon.de` and prints the `signed_in` field from the structured result. Returns `SessionStatus` with `signed_in`, `site`, `default`, `sign_in` advice, `error`, and `sites`. ```python result = await call("sign_in", {"site": "amazon.de"}) print(result.structured_content["signed_in"]) # True ``` -------------------------------- ### update_config error handling example Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/session.md Example of catching AmazonOrdersError when update_config is called with an invalid key. The error message includes the list of valid settings. ```python from amazonorders.exception import AmazonOrdersError try: session.update_config("not_a_key", 1) except AmazonOrdersError as e: print(e) # '"not_a_key" isn't a setting that can be changed. Settings that can: domain, browser, ...' ``` -------------------------------- ### XMLHttpRequest Polyfill and Environment Setup Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/tests/resources/orders/order-history-2018-0.html Sets up environment variables and polyfills for XMLHttpRequest. ```javascript function(e,t,n){ ``` ```javascript "use strict";(function(r){var A;function o(e){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)} // Jaime Pillora - MIT Copyright 2018 n(24),n(13),n(6),n(141),n(26),n(101),n(16),function(n){var i,a,u,c,s,f,g,l,d,p,I,y,h,C,B,E,v,Q,w,m,b,x,S,D,k,R,F=[].indexOf||function(e){for(var t=0,n=this.length;t ASGIApp: ``` -------------------------------- ### SavedSession.run Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/session.md Runs a callable with a site's signed-in session, retrying once if the saved session changed after an authentication error. Resolves the site, gets or creates its session, and holds its lock during the call. ```APIDOC ## SavedSession.run ### Description Runs a callable with a site's signed-in session, retrying once if the saved session changed after an authentication error. Resolves the site, gets or creates its session, and holds its lock during the call. ### Method `run` ### Parameters - `call` (Callable[[AmazonSession], T]) - Required - The callable to execute with the signed-in session. - `site` (Optional[str]) - Optional - Amazon site (e.g., `amazon.de`); defaults to the config's `domain`. ### Returns `T` - The result of the callable. ### Raises - `AmazonOrdersAuthError` - If no saved session or session expired. - `AmazonOrdersError` - If the site cannot be read. ### Example ```python session = SavedSession() year = session.run(lambda s: AmazonOrders(s).get_orders(year=2024), "amazon.de") ``` ``` -------------------------------- ### Reuse schema functions in create_server() Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/schema.md Shows how to import and use SCHEMA, ToolOutput, and tool_description from amazonorders_mcp.schema. The example asserts tool_description returns the schema description for a tool, prints a property from the output schema, and rebuilds a tool result by subclassing ToolOutput and validating a dict. ```python from amazonorders_mcp.schema import SCHEMA, ToolOutput, tool_description assert tool_description("get_orders") == SCHEMA["tools"]["get_orders"]["description"] print(SCHEMA["tools"]["get_order"]["output_schema"]["properties"]["order_number"]) # Rebuild any tool result from an amazon-orders entity dict, keeping the generated output schema: class MyOrdersPage(ToolOutput): tool = "get_orders" page = MyOrdersPage.model_validate({"items": [...], "cursor": None, "has_more": False}) ``` -------------------------------- ### Calling get_transactions with days=90 Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/tools.md Example invocation of the get_transactions tool with a 90-day window, printing the first transaction amount and the has_more flag from the returned page. ```python page = await call("get_transactions", {"days": 90}) print(page.structured_content["items"][0]["amount"], page.structured_content["has_more"]) ``` -------------------------------- ### Compose server with additional instructions Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/server.md Creates a server with custom instructions appended to the default INSTRUCTIONS after a single space. Empty or whitespace-only values leave instructions unchanged. ```python server = create_server(additional_instructions="This server also offers inventory tools.") ``` -------------------------------- ### Create and run server Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/server.md Imports create_server, creates a server instance, and runs it over stdio. The server is named "amazon-orders" with version __version__ and log level "WARNING". ```python from amazonorders_mcp.server import create_server server = create_server() server.run() # stdio ``` -------------------------------- ### GET /health Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/endpoints.md Health check endpoint that returns a simple 'ok' response. It is used for health checks by Dockerfile examples and proxies, and it never calls Amazon. ```APIDOC ## [GET] /health ### Description Health check endpoint that returns a simple 'ok' response. It is used for health checks by Dockerfile examples and proxies, and it never calls Amazon. ### Method GET ### Endpoint /health ### Response #### Success Response (200) - **body** (text/plain) - "ok" #### Response Example ok ``` -------------------------------- ### main(args=None) Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/server.md Console entry point for the amazon-orders-mcp server. Parses CLI arguments, builds the MCP server, and runs it over stdio or Streamable HTTP. ```APIDOC ## main(args=None) ### Description Console entry point (`amazon-orders-mcp`). Parses arguments with `_parse_args`, builds the server with `create_server()`, then either runs over stdio (`server.run()`) or serves Streamable HTTP via `uvicorn.run` with `server.settings.log_level.lower()`. ### Method main ### Parameters #### CLI Arguments - **--transport** (`"stdio"` | `"streamable-http"`) - Default: `"stdio"` - Transport; HTTP serves at `/mcp`, with `GET /health` health checks - **--host** (`str`) - Default: `"127.0.0.1"` - HTTP bind address; on loopback only loopback `Host` headers are served - **--port** (`int`) - Default: `8000` - HTTP port - **--json-response** (flag) - Default: `False` - JSON responses instead of an event stream (no progress) - **--token-file** (`str` path) - Default: `None` - File holding the bearer token; mutually exclusive with the env var - **env `AMAZON_ORDERS_MCP_TOKEN`** (`str`) - Default: `None` - Bearer token, alternative to `--token-file` ### Usage ```python from amazonorders_mcp.server import main main(["--transport", "streamable-http", "--host", "0.0.0.0", "--token-file", "/run/secrets/token"]) ``` ``` -------------------------------- ### main() function signature Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/server.md Console entry point for the amazon-orders-mcp server. Parses arguments with _parse_args, builds the server with create_server(), then runs over stdio or serves Streamable HTTP via uvicorn.run. ```python def main(args: Optional[List[str]] = None) -> None: ``` -------------------------------- ### Get Own Property Symbols Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/tests/resources/orders/order-history-2018-0.html Exports the function to get own property symbols. ```javascript function(e,t){t.f=Object.getOwnPropertySymbols} ``` -------------------------------- ### Build and Run Amazon Orders MCP in Docker Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/README.md Build the Docker image and run it with a volume mount for configuration persistence. Sign in using the login target first as the container lacks a display. ```sh docker build -t amazon-orders-mcp . docker run -i --rm -v amazon-orders:/home/app/.config/amazonorders amazon-orders-mcp ``` -------------------------------- ### create_server(saved_session=None, *, additional_instructions="") Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/server.md Creates the MCPServer named 'amazon-orders' with all tools registered. Optionally accepts a SavedSession and additional instructions for composing with other tools. ```APIDOC ## create_server(saved_session=None, *, additional_instructions="") ### Description Creates the `MCPServer` named `"amazon-orders"` (version `__version__`, log level `"WARNING"`) with every tool registered. `additional_instructions`, when stripped of surrounding whitespace, is appended to `INSTRUCTIONS` after a single space; empty or whitespace-only values leave the instructions unchanged. ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `saved_session` | `Optional[SavedSession]` | no | `None` | The session the tools use; `None` creates a `SavedSession()` using the CLI's saved config and cookie jars | | `additional_instructions` | `str` | no | `""` | Instructions appended to the defaults, for applications composing the server with other tools | ### Returns `MCPServer` (`mcp.server.mcpserver`), with tools registered under the names `sign_in`, `get_orders`, `search_orders`, `get_order`, `get_tracking`, `get_invoices`, `get_family_members`, `get_transactions`, `get_gift_cards`, `get_prime_payments`, `check_session`, `get_config`, `update_config`. ### Raises None directly; tool calls raise `ToolError` (see [errors.md](../errors.md)). ### Usage ```python from amazonorders_mcp.server import create_server server = create_server() server.run() # stdio ``` Composing with other tools: ```python server = create_server(additional_instructions="This server also offers inventory tools.") ``` ``` -------------------------------- ### sites() -> List[str] Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/session.md Returns the default site, then every other site with a saved session (a cookie jar on disk), sorted, signed in or not. If AMAZON_DOMAIN is set in the environment, returns just the default site (a pinned environment outranks all config). ```APIDOC ## sites() -> List[str] ### Description The default site, then every other site with a saved session (a cookie jar on disk), sorted, signed in or not. If `AMAZON_DOMAIN` is set in the environment, returns just the default site (a pinned environment outranks all config). ### Method sites ### Returns List[str] - List of site names. ``` -------------------------------- ### Bootstrap CSD functionality Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/tests/resources/orders/order-history-2018-0.html Provides functions for bootstrapping, uninstalling, disabling, and checking the installation status of the CSD module. ```javascript Promise((function(n,r){var A=s.apply(e,t);function i(e){o(A,n,r,i,a,"next",e)}function a(e){o(A,n,r,i,a,"throw",e)}i(undefined)}))},function(){return f.apply(this,arguments)})}\])&&u(t.prototype,n),i&&u(t,i),e}();t.LocalStorage=s},function(e,t,n){"use strict";n(6),Object.defineProperty(t,"\_\_esModule",{value:!0}),t.csdBootstrap=function(){return g.apply(this,arguments)},t.csdUninstall=l,t.csdDisable=function(){c.disable(),u.updateCounter("Siege:Csd:Bootstrap:Disable",1)},t.csdIsInstalled=p,t.csdIsDisabled=y,n(12);var r=n(27),A=n(70),o=n(170);function i(e,t,n,r,A,o,i){try{var a=e\[o\](i),u=a.value}catch(c){return void n(c)}a.done?t(u):Promise.resolve(u).then(r,A)}function a(e){return function(){var t=this,n=arguments;return new Promise((function(r,A){var o=e.apply(t,n);function a(e){i(o,r,A,a,u,"next",e)}function u(e){i(o,r,A,a,u,"throw",e)}a(undefined)}))}}var u=new(n(17).Logger),c=new A.KeyManager;function s(){return f.apply(this,arguments)}function f(){return(f=a(regeneratorRuntime.mark((function e(){var t,n;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,l();case 2:return t=new o.CompatibilityValidator,e.next=5,t.validateBeforeInstall();case 5:return e.next=7,c.createKey();case 7:if((n=e.sent)===(0,r.cookieManagerGet)().kid){e.next=10;break}throw new Error("Cookie Manager does not return the new key after creation (expected ".concat(n,", got ").concat((0,r.cookieManagerGet)().kid,")"));case 10:return e.next=12,t.validateAfterInstall();case 12:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function g(){return(g=a(regeneratorRuntime.mark((function e(){return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,p();case 2:if(e.t0=e.sent,!e.t0){e.next=5;break}e.t0=(0,r.cookieManagerGet)().wasmTested;case 5:if(!e.t0){e.next=13;break}return u.updateCounter("Siege:Csd:Bootstrap:Skip:AlreadyInstalled",1),u.updateCounter("Siege:Csd:Bootstrap:Success",1),e.next=10,c.rotateKeyIfNeeded();case 10:return e.sent?u.updateCounter("Siege:Csd:Bootstrap:KeyRotated",1):u.updateCounter("Siege:Csd:Bootstrap:KeyRotated",0),e.abrupt("return");case 13:return e.next=15,y();case 15:if(!e.sent){e.next=18;break}return u.updateCounter("Siege:Csd:Bootstrap:Skip:Disabled",1),e.abrupt("return");case 18:return e.next=20,s();case 20:u.updateCounter("Siege:Csd:Bootstrap:Success",1),u.updateCounter("Siege:Csd:Bootstrap:NewUser",1);case 22:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function l(){return d.apply(this,arguments)}function d(){return(d=a(regeneratorRuntime.mark((function e(){var t,n=arguments;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=n.length>0&&n\[0\]!==undefined&&n\[0\],e.next=3,c\["delete"\](t);case 3:return e.next=5,p();case 5:if(!e.sent){e.next=7;break}throw new Error("csdIsInstalled still returned true after uninstall");case 7:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function p(){return I.apply(this,arguments)}function I(){return(I=a(regeneratorRuntime.mark((function e(){return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",c.isInitialized());case 1:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function y(){return h.apply(this,arguments)}function h(){return(h=a(regeneratorRuntime.mark((function e(){return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",c.isDisabled());case 1:case"end":return e.stop()}}),e)})))).apply(this,arguments)}} ``` -------------------------------- ### Species Property Setup Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/tests/resources/orders/order-history-2018-0.html Configures the @@species property on a constructor, allowing derived classes to return instances of the base class. ```javascript function(e,t,n){ ``` ```javascript "use strict";var r=n(21),A=n(5),o=n(2),i=n(8),a=o("species");e.exports=function(e){var t=r(e),n=A.f;i&&t&&!t[a]&&n(t,a,{configurable:!0,get:function(){return this}})}} ``` -------------------------------- ### site(site=None) -> str Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/session.md Resolves a site to its canonical name (amazon., e.g. amazon.de); empty or None gives the config's domain. Accepts identifiers check_session returns (base URLs, e.g. https://www.amazon.de). ```APIDOC ## site(site=None) -> str ### Description Resolve a site to its canonical name (`amazon.`, e.g. `amazon.de`); empty or `None` gives the config's `domain`. Accepts identifiers `check_session` returns (base URLs, e.g. `https://www.amazon.de`). ### Method site ### Parameters - **site** (Optional[str]) - Optional - The site identifier to resolve; if None, uses the config's domain. ### Returns str - The canonical site name (e.g., `amazon.de`). ### Raises `AmazonOrdersError` if the site isn't an Amazon site that can be read. ``` -------------------------------- ### Call get_tracking with invalid shipment ID Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/tools.md Example of calling get_tracking with an invalid shipment ID, handling the error result. ```python result = await call("get_tracking", {"order_id": "112-0399923-3070642", "shipment_id": "999"}) if result.is_error: print(result.content) # signed-in/site/Amazon errors surface here ``` -------------------------------- ### Call get_order with invalid order ID Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/tools.md Example of calling get_order with an invalid order ID, expecting an error result. ```python result = await call("get_order", {"order_id": "999-0000000-0000000"}) assert result.is_error # no saved session, or Amazon error described in result.content ``` -------------------------------- ### Build ISS Initialization Object Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/tests/resources/orders/order-details-112-0399923-3070642.html Constructs the configuration object required for the search service, including session, market, and feature flag settings. ```javascript function buildIssInitObject(opts, issOpts, isNewIss) { var issInitObj = { src: opts.host , sessionId: opts.sessionId , requestId: opts.requestId , mkt: opts.marketId , obfMkt: opts.obfuscatedMarketId , pageType: opts.pageType , language: opts.language , customerId: opts.customerId , fresh: opts.fresh , b2b: opts.b2b , aliases: opts.searchAliases , fb: issOpts.fallbackFlag , isDigitalFeaturesEnabled: issOpts.isDigitalFeaturesEnabled , isWayfindingEnabled: issOpts.isWayfindingEnabled , issPrimeEligible: issOpts.issPrimeEligible , deptText: issOpts.departmentText , sugText: issOpts.suggestionText , filterAliases: opts.filterAliases , biaWidgetUrl: opts.biaWidgetUrl , recentSearchesTreatment: issOpts.recentSearchesTreatment , authorSuggestionText: issOpts.authorSuggestionText , translatedStringsMap: issOpts.translatedStringsMap , biaTitleText: "" , biaPurchasedText: "" , biaViewAllText: "" , biaViewAllManageText: "" , biaAndText: "" , biaManageText: "" , biaWeblabTreatment: "" , issNavConfig: issOpts.issNavConfig , cf: issOpts.cf , ime: opts.isJpOrCn , mktid: opts.marketId , qs: opts.isJpOrCn , issCorpus: issOpts.issCorpus , deepNodeISS: { searchAliasAccessor: function($) { return (window.SearchPageAccess && window.SearchPageAccess.searchAlias()) || $('select.searchSelect').children().attr('data-root-alias'); }, searchAliasDisplayNameAccessor: function() { return (window.SearchPageAccess && window.SearchPageAccess.searchAliasDisplayName()); } } , removeDeepNodeISS: issOpts.removeDeepNodeISS , trendingTreatment: issOpts.trendingTreatment , useAPIV2: issOpts.useAPIV2 , opfSwitch: issOpts.opfSwitch , isISSDesktopRefactorEnabled: issOpts.isISSDesktopRefactorEnabled , useServiceHighlighting: issOpts.useServiceHighlighting , isInternal: issOpts.isInternal , isAPICachingDisabled: issOpts.isAPICachingDisabled , isBrowseNodeScopingEnabled: issOpts.isBrowseNodeScopingEnabled , isStorefrontTemplateEnabled: issOpts.isStorefrontTemplateEnabled , disableAutocompleteOnFocus: issOpts.disableAutocompleteOnFocus , asin: opts.asin }; // If we aren't using the new ISS then we need to add these properties if (!isNewIss) { issInitObj.dd = issOpts.dropdown; // The element with id searchDropdownBox doesn't exist in C. issInitObj.imeSpacing = issOpts.imeSpacing; issInitObj.isNavInline = 1; issInitObj.triggerISSOnClick = 0; issInitObj.sc = 1; issInitObj.np = issOpts.np; } return issInitObj; } // END buildIssInitObject ``` -------------------------------- ### SavedSession __init__ method Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/session.md Initializes a SavedSession with an optional AmazonOrdersConfig. If config is None, uses the same one the amazon-orders CLI uses. Instance state includes config, _site_sessions dict, and a threading.Lock. ```python def __init__(self, config: Optional[AmazonOrdersConfig] = None) -> None: ``` -------------------------------- ### State management utility Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/tests/resources/orders/order-history-2018-0.html Provides methods to set, get, and check state associated with objects, using WeakMap if available or a fallback property. ```javascript function(e,t,n){var r,A,o,i=n(116),a=n(0),u=n(3),c=n(10),s=n(4),f=n(58),g=n(38),l=a.WeakMap;if(i){var d=new l,p=d.get,I=d.has,y=d.set;r=function(e,t){return y.call(d,e,t),t},A=function(e){return p.call(d,e)||{}},o=function(e){return I.call(d,e)}}else{var h=f("state");g[h]=!0,r=function(e,t){return c(e,h,t),t},A=function(e){return s(e,h)?e[h]:{}},o=function(e){return s(e,h)}}e.exports={set:r,get:A,has:o,enforce:function(e){return o(e)?A(e):r(e,{})},getterFor:function(e){return function(t){var n;if(!u(t)||(n=A(t)).type!==e)throw TypeError("Incompatible receiver, "+e+" required");return n}}}} ``` -------------------------------- ### Execute Mobile Performance Timing Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/tests/resources/orders/order-history-2018-0.html This module manages performance timing for mobile transitions, including handling navigation starts and view transitions. ```javascript var ue_mbl=ue_csm.ue.exec(function(h,a){function s(c){b=c||{};a.AMZNPerformance=b;b.transition=b.transition||{};b.timing=b.timing||{};if(a.csa){var d;b.timing.transitionStart&&(d=b.timing.transitionStart);b.timing.processStart&&(d=b.timing.processStart);d&&(csa("PageTiming")("mark","nativeTransitionStart",d),csa("PageTiming")("mark","transitionStart",d))}h.ue.exec(t,"csm-android-check")()&&b.tags instanceof Array&&(c=-1!=b.tags.indexOf("usesAppStartTime")||b.transition.type?!b.transition.type&&-1< b.tags.indexOf("usesAppStartTime")?"warm-start":void 0:"view-transition",c&&(b.transition.type=c));n=null;"reload"===e._nt&&h.ue_orct||"intrapage-transition"===e._nt?u(b):"undefined"===typeof e._nt&&f&&f.timing&&f.timing.navigationStart&&a.history&&"function"===typeof a.History&&"object"===typeof a.history&&a.history.length&&1!=a.history.length&&(b.timing.transitionStart=f.timing.navigationStart);p&&e.ssw(q,""+(b.timing.transitionStart||n||""));c=b.transition;d=e._nt?e._nt:void 0;c.subType=d;a.ue&& a.ue.tag&&a.ue.tag("has-AMZNPerformance");e.isl&&a.uex&&a.uex("at","csm-timing");v()}function w(c){a.ue&&a.ue.count&&a.ue.count("csm-cordova-plugin-failed",1)}function t(){return a.cordova&&a.cordova.platformId&&"android"==a.cordova.platformId}function u(){if(p){var c=e.ssw(q),a=function(){},x=e.count||a,a=e.tag||a,k=b.timing.transitionStart,g=c&&!c.e&&c.val;n=c=g?+c.val:null;k&&g&&k>c?(x("csm.jumpStart.mtsDiff",k-c||0),a("csm-rld-mts-gt")):k&&g?a("csm-rld-mts-leq"):g?k||a("csm-rld-mts-no-new"):a("csm-rld-mts-no-old")}f&& f.timing&&f.timing.navigationStart?b.timing.transitionStart=f.timing.navigationStart:delete b.timing.transitionStart}function v(){try{a.P.register("AMZNPerformance",function(){return b})}catch(c){}}function r(){if(!b)return"";ue_mbl.cnt=null;var c=b.timing,d=b.transition,d=["mts",l(c.transitionStart),"mps",l(c.processStart),"mtt",d.type,"mtst",d.subType,"mtlt",d.launchType];a.ue&&a.ue.tag&&(c.fr_ovr&&a.ue.tag("fr_ovr"),c.fcp_ovr&&a.ue.tag("fcp_ovr"),d.push("fr_ovr",l(c.fr_ovr),"fcp_ovr",l(c.fcp_ovr))); for(var c="",e=0;e MCPServer: ``` -------------------------------- ### Call get_order with valid order ID Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/tools.md Example of calling get_order with a valid order ID and printing the grand_total from the structured content. ```python order = await call("get_order", {"order_id": "112-0399923-3070642"}) print(order.structured_content["grand_total"]) ``` -------------------------------- ### Initialize SPA and Page Transition Handling Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/tests/resources/orders/order-history-2018-0.html Registers the SPA plugin and manages page transitions, including state tracking and lifecycle events like loading and unloading. ```javascript v.visibilityState||"unknown"})),w(v,c,R(p+c)),w(v,s,R(p+s)),y.when&&y.when("mash").execute(function(e){e&&(w(e,"appPause",R(f+"pause")),w(e,"appResume",R(f+"resume")),R(f+"deviceready")(),$.cordova&&$.cordova.platformId&&R(f+cordova.platformId)(),w(v,d,R(f+d)),w(v,l,R(f+l)))}),e=$.app||{},n=b(function(){k(f+"willDisappear"),D()}),a=typeof(t=e[u])==i,e[u]=b(function(){n(),a&&t()}),$.app||($.app=e),"complete"===v.readyState?A():w($,"load",A),E?S():x(),o.on("$app.blur",S),o.on("$app.focus",x),o.on("$document.blur",S),o.on("$document.focus",x),o.on("$document.hidden",S),o.on("$document.visible",x),o.register("SPA",{newPage:I}),I({transitionType:{0:"hard",1:"refresh",2:"back-button"}[P]||"unknown"}));function I(n,e){var t=!!r,a=(e=e||{}).keepPageAttributes;t&&(k("$beforePageTransition"),k("$pageTransition")),t&&!a&&g("removeEntity","page"),r=o.UUID(),a?T.id=r:T={schemaId:".PageEntity.2",id:r,url:m?h.href.split("?")[0]:h.href,server:h.hostname,path:h.pathname,referrer:m?v.referrer.split("?")[0]:v.referrer,title:v.title},Object.keys(n||{}).forEach(function(e){T[e]=n[e]}),g("setEntity",{page:T}),k("$pageChange",T,{buffered:1}),t&&k("$afterPageTransition")}function A(){k("$load"),k("$ready"),k("$afterload")}function D(){k("$ready"),k("$beforeunload"),k("$unload"),k("$afterunload")}function S(){E||(k("$visible",!1,{buffered:1}),E=!0)}function x(){E&&(k("$visible",!0,{buffered:1}),E=!1)}function R(n,t){return b(function(){var e=typeof t==i?n+t():n;k(e)})}}); ``` -------------------------------- ### Call update_config with valid key Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/tools.md Example of updating the request_timeout setting to 45 with save=True. The result contains the key, value, and saved flag. ```python result = await call("update_config", {"key": "request_timeout", "value": 45, "save": True}) print(result.structured_content) # {'key': 'request_timeout', 'value': 45, 'saved': True} ``` -------------------------------- ### SavedSession get_config method Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/session.md Returns the current value of each key in PREFERENCE_KEYS and TUNING_KEYS, read from the live config. ```python def get_config(self) -> Dict[str, Dict[str, Any]]: ``` -------------------------------- ### check_session call with site parameter Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/tools.md Calls check_session with a specific site to get sign-in advice when signed out. The output shows sign_in is None while signed in. ```python result = await call("check_session", {"site": "amazon.de"}) # sign-in advice per site when signed out print(result.structured_content["sign_in"]) # None while signed in ``` -------------------------------- ### search_orders error handling example Source: https://github.com/alexdlaird/amazon-orders-mcp/blob/develop/_autodocs/api-reference/tools.md Demonstrates checking for an error response from search_orders. If the result is an error, it prints the error content, such as a message about no saved Amazon session. ```python result = await call("search_orders", {"query": "trowel"}) if result.is_error: print(result.content) # e.g. "There's no saved Amazon session. Offer to sign the user in ..." ```